我有一个滚动视图和一个放在它上面的按钮,当我添加一个点击手势识别器时按钮不起作用。有没有办法限制点按仅滚动视图而不是按钮,这样按钮功能正常。
这是我的代码
UITapGestureRecognizer* tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapGesture:)];
tap.numberOfTapsRequired = 1;
tap.numberOfTouchesRequired = 1;
[scroll addGestureRecognizer:tap];
[tap release];
- (void)tapGesture:(UIGestureRecognizer*)gesture{
NSLog(@"scroll tapped");
}
答案 0 :(得分:2)
如果你这样做
tap.cancelsTouchesInView = NO;
它将允许按下按钮。但是,当您按下按钮时,将同时按下按钮检测到水龙头。要避免这种情况,您必须继承UIScrollView
并实现以下方法 -
- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event {
for ( UIView * subview in self.subviews ) {
UIView * hitView = [subview hitTest:point withEvent:event];
if ( hitView )
return hitView;
}
return [super hitTest:point withEvent:event];
}
实现上述方法会将触摸传递给滚动视图的子视图。
答案 1 :(得分:0)
无需子类化Scrollview。以下代码轻松解决了问题。方法 gestureRecognizer:shouldReceiveTouch:可以解决问题。
UITapGestureRecognizer* tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapGesture:)];
tap.numberOfTapsRequired = 1;
tap.numberOfTouchesRequired = 1;
tap.delegate = self;
tap.cancelsTouchesInView = NO;
[scroll addGestureRecognizer:tap];
[tap release];
-(BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch {
if (scroll.superview != nil) {
if ([touch.view isKindOfClass:[UIButton class]])
{
return NO; // ignore the touch
}
}
return YES; // handle the touch
}
- (void)tapGesture:(UIGestureRecognizer*)gesture {
NSLog(@"scroll tapped");
}