Ios 从UITapGestureRecognitor中排除子视图

Ios 从UITapGestureRecognitor中排除子视图,ios,objective-c,cocoa-touch,Ios,Objective C,Cocoa Touch,我有一个子视图和一个超级视图。superview附带了一个UITapGestureRecognitor UIView *superview = [[UIView alloc] initWithFrame:CGRectMake:(0, 0, 320, 480); UIView *subview = [[UIView alloc] initWithFrame:CGRectMake:(100, 100, 100, 100); UIPanGestureRecognizer *recognizer = [

我有一个子视图和一个超级视图。superview附带了一个UITapGestureRecognitor

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];
识别器也在子视图中启动,是否有方法将识别器从子视图中排除




我知道以前有人问过这个问题,但我没有找到好的答案。

您可以使用手势识别器委托来限制它可以识别触摸的区域,类似于此示例:

recognizer.delegate = self;
...

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch{
    CGPoint touchPoint = [touch locationInView:superview];
    return !CGRectContainsPoint(subview.frame, touchPoint);
}
注意,您需要保持对父视图和子视图的引用(使它们成为实例变量?),以便能够在委托方法中使用它们

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
{
    if(touch.view == yourSubview)
    {
        return NO;
    }
    else
    {
        return YES;
    }
}

谢谢:

对于Swift 3,您可以使用
查看.包含(点)
而不是
cRectContainsPoint

func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
    if yourSubview.frame.contains(touch.location(in: view)) {
        return false
    }
    return true
}