从UITapGestureRecognizer排除子视图
我有一个子视图和超视图。 超级视图附有一个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];
识别器是在子视图内被触发的,有没有办法从子视图中排除识别器?
我知道这个问题之前已经被问过了,但是我没有find一个好的答案。
您可以使用手势识别器代理来限制可以识别类似于此示例的触摸的区域:
recognizer.delegate = self; ... - (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch{ CGPoint touchPoint = [touch locationInView:superview]; return !CGRectContainsPoint(subview.frame, touchPoint); }
请注意,您需要保持对父视图和子视图的引用(使其成为实例variables?)才能在委托方法中使用它们
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch { if(touch.view == yourSubview) { return NO; } else { return YES; } }
感谢: https : //stackoverflow.com/a/19603248/552488
对于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 }