iOS:截取从顶视图到底视图的轻击手势事件

Han*_*gbo 5 cocoa-touch objective-c ios

在我的视图控制器中,我向self.view添加了一个UITapGestureRecognizer.我在self.view上添加了一个小视图.当我点击小视图时,我不想在self.view中触发UITapGestureRecognizer事件.这是我的代码,它不起作用.

    - (void)viewDidLoad {
    [super viewDidLoad];

    UITapGestureRecognizer *_tapOnVideoRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(toggleControlsVisible)];

    [self.view addGestureRecognizer:_tapOnVideoRecognizer];

    UIView *smallView=[[UIView alloc] initWithFrame:CGRectMake(0, 0, 200, 200)];
    smallView.backgroundColor=[UIColor redColor];
    smallView.exclusiveTouch=YES;
    smallView.userInteractionEnabled=YES;

    [self.view addSubview:smallView];
    }

    - (void)toggleControlsVisible
    {
        NSLog(@"tapped");
    }
Run Code Online (Sandbox Code Playgroud)

当我点击小视图时,它仍会在self.view中触发点击事件.Xcode记录"轻拍".如何拦截从smallView到self.view的手势事件?

gab*_*ler 8

像这样实现UIGestureRecognizer委托方法shouldReceiveTouch.如果触摸位置在topView内,请勿接触.

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
{
    CGPoint location = [touch locationInView:self.view];

    if (CGRectContainsPoint(self.topView.frame, location)) {
        return NO;
    }
   return YES;
}
Run Code Online (Sandbox Code Playgroud)