我有子视图和超级视图。 superview附加了一个UITapGestureRecognizer。
UIView *superview = [[UIView alloc] initWithFrame:CGRectMake:(0, 0, 320, 480);
UIView *subview = [[UIView alloc] initWithFrame:CGRectMake:(100, 100, 100, 100);
UIPanGestureRecognizer *recognizer = [[UIPanGestureRecognizer alloc] initWithTarget: self action: @selector(handleTap);
superview.userInteractionEnabled = YES;
subview.userInteractionEnabled = NO;
[superview addGestureRecognizer:recognizer];
[self addSubview:superview];
[superview addSubview:subview];
识别器也会在子视图中触发,有没有办法从子视图中排除识别器?
我知道之前已经问过这个问题,但我找不到合适的答案。
答案 0 :(得分:16)
您可以使用手势识别器委托来限制可识别触摸的区域,类似于此示例:
recognizer.delegate = self;
...
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch{
CGPoint touchPoint = [touch locationInView:superview];
return !CGRectContainsPoint(subview.frame, touchPoint);
}
请注意,您需要继续引用父视图和子视图(使它们成为实例变量吗?)才能在委托方法中使用它们
答案 1 :(得分:3)
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
{
if(touch.view == yourSubview)
{
return NO;
}
else
{
return YES;
}
}
答案 2 :(得分:2)
对于Swift 3,您可以使用view.contains(point)
代替CGRectContainsPoint
。
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
if yourSubview.frame.contains(touch.location(in: view)) {
return false
}
return true
}