2013-10-06 102 views
0

我想要建立一個簡單的UIScrollView與分頁,以在3個圖像之間水平滾動。 棘手的部分是,我希望每個圖像可點擊並捕捉點擊事件。添加UIButtons作爲子視圖時UIScrollView不滾動

我的技巧是創建3個UIButton,每個UIButton包含UIImage。給每個按鈕一個標籤並設置一個動作。

問題:我可以捕獲點擊事件 - 但是它不可滾動!

這裏是我的代碼:

- (void) viewDidAppear:(BOOL)animated { 

    _imageArray = [[NSArray alloc] initWithObjects:@"content_01.png", @"content_02.png", @"content_03.png", nil]; 

    for (int i = 0; i < [_imageArray count]; i++) { 
     //We'll create an imageView object in every 'page' of our scrollView. 
     CGRect frame; 
     frame.origin.x = _contentScrollView.frame.size.width * i; 
     frame.origin.y = 0; 
     frame.size = _contentScrollView.frame.size; 

     // 
     //get the image to use, however you want 
     UIImage* image = [UIImage imageNamed:[_imageArray objectAtIndex:i]]; 

     UIButton* button = [[UIButton alloc] initWithFrame:frame]; 

     //set the button states you want the image to show up for 
     [button setImage:image forState:UIControlStateNormal]; 
     [button setImage:image forState:UIControlStateHighlighted]; 

     //create the touch event target, i am calling the 'productImagePressed' method 
     [button addTarget:self action:@selector(imagePressed:) 
     forControlEvents:UIControlEventTouchUpInside]; 
     //i set the tag to the image #, i was looking though an array of them 
     button.tag = i; 

     [_contentScrollView addSubview:button]; 
    } 

    //Set the content size of our scrollview according to the total width of our imageView objects. 
    _contentScrollView.contentSize = CGSizeMake(_contentScrollView.frame.size.width * [_imageArray count], _contentScrollView.frame.size.height); 

    _contentScrollView.backgroundColor = [ENGAppDelegate backgroundColor]; 
    _contentScrollView.delegate = self; 
} 
+0

您是否已通過代碼確保_contentScrollView.contentSize是您的期望?我認爲_contentScrollView.frame.size在這一點上計算不正確,所以你不會得到很好的價值。 – HalR

+0

我查過了,計算正確!讓我這樣說:如果我沒有框架啓動按鈕(所以沒有圖片顯示),然後我看到它滾動! – Shvalb

+0

是否有可能,如果我設置的按鈕框架像ScrollView的確切大小,那麼它完全阻止滾動,所以我沒有得到滾動事件? – Shvalb

回答

1

好吧,既然UIButtonUIControl子類,它 「吃掉」 你的滾動視圖的觸摸:

[UIScrollView touchesShouldCancelInContentView:]默認返回值是YES如果視圖不是UIControl對象;否則,它返回NO。

(從https://developer.apple.com/library/ios/documentation/uikit/reference/UIScrollView_Class/Reference/UIScrollView.html#//apple_ref/occ/instm/UIScrollView/touchesShouldCancelInContentView :)通過繼承UIScrollView和覆蓋touchesShouldCancelInContentView:(和/或touchesShouldBegin:withEvent:inContentView:

可能影響這一點。但是,對於您的用例,我不會首先使用按鈕。爲什麼不只是在滾動視圖中添加輕擊手勢識別器並使用觸點來確定哪個圖像已被輕敲?這很容易,應該沒有任何問題。

相關問題