Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS: Intercept tap gesture event from top view to bottom view

In my view controller, I add a UITapGestureRecognizer to self.view. And I add a small view on top of self.view. When I tap the small view, I don't want to trigger the UITapGestureRecognizer event in self.view. Here is my code, it doesn't work.

    - (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");
    }

When I tap the small view, it still triggers the tap event in self.view. Xcode logs "tapped". How to intercept the gesture event from smallView to self.view?

like image 847
Han Pengbo Avatar asked Dec 27 '14 02:12

Han Pengbo


1 Answers

Implement UIGestureRecognizer delegate method shouldReceiveTouch like this. If touch location is inside topView, do not receive the touch.

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

    if (CGRectContainsPoint(self.topView.frame, location)) {
        return NO;
    }
   return YES;
}
like image 128
gabbler Avatar answered Sep 21 '22 20:09

gabbler