我试图构建一个简单的UIScrollView,分页到3个图像之间水平滚动。棘手的部分是,我希望每个图像将是可点击和捕捉点击事件。
我的技术是创建3个UIButtons,每个UIImage由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;
}发布于 2013-10-06 21:20:09
因为UIButton是一个UIControl子类,所以它“吞噬”了滚动视图的触感:
[UIScrollView touchesShouldCancelInContentView:]如果视图不是UIControl对象,则默认返回值为YES;否则,它将返回NO。
(来自ref/occ/instm/UIScrollView/touchesShouldCancelInContentView:)
您可以通过子类UIScrollView和覆盖touchesShouldCancelInContentView: (和/或touchesShouldBegin:withEvent:inContentView:)来影响这一点。但是,对于您的用例,我首先不会使用按钮。为什么不添加一个点击手势识别器到滚动视图,并使用触摸点,以确定哪个图像已被点击?这要容易得多,而且应该没有任何问题。
发布于 2022-04-17 09:32:46
这完全解决了这个问题:
scrollview.panGestureRecognizer.delaysTouchesBegan = YES;https://stackoverflow.com/users/904365/kjuly在本主题中提供了正确的答案:ScrollView/TableView with UIControl/UIButton subviews not scrollable under iOS 8
https://stackoverflow.com/questions/19213118
复制相似问题