我想要建立一個簡單的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;
}
您是否已通過代碼確保_contentScrollView.contentSize是您的期望?我認爲_contentScrollView.frame.size在這一點上計算不正確,所以你不會得到很好的價值。 – HalR
我查過了,計算正確!讓我這樣說:如果我沒有框架啓動按鈕(所以沒有圖片顯示),然後我看到它滾動! – Shvalb
是否有可能,如果我設置的按鈕框架像ScrollView的確切大小,那麼它完全阻止滾動,所以我沒有得到滾動事件? – Shvalb