在我的视图控制器中,我向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,200,200)]; smallView.backgroundColor=[UIColor redColor]; smallView.exclusivetouch=YES; smallView.userInteractionEnabled=YES; [self.view addSubview:smallView]; } - (void)toggleControlsVisible { NSLog(@"tapped"); }
当我点击小视图时,它仍会在self.view中触发点击事件. Xcode记录“轻拍”.如何拦截从smallView到self.view的手势事件?
解决方法
像这样实现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; }