Exclude subviews from UIGestureRecognizer
I used the simple way below. It works perpectly!
Implement UIGestureRecognizerDelegate function, accept only touchs on superview, not accept touchs on subviews:
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
{
if (touch.view != _mySuperView) { // accept only touchs on superview, not accept touchs on subviews
return NO;
}
return YES;
}
I managed to get it working by doing the following:
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapGestureHandler:)];
// ...
-(void) tapGestureHandler:(UITapGestureRecognizer *)sender {
CGPoint point = [sender locationInView:sender.view];
UIView *viewTouched = [sender.view hitTest:point withEvent:nil];
if ([viewTouched isKindOfClass:[ThingIDontWantTouched class]]) {
// Do nothing;
} else {
// respond to touch action
}
}
iOS 6 introduces a great new feature that solves this exact problem - a UIView (subview) can return NO from gestureRecognizerShouldBegin:
(gesture recognizer attached to a superview). Indeed, that is the default for some UIView subclasses with regard to some gesture recognizers already (e.g. a UIButton with regard to a UITapGestureRecognizer attached to a superview).
See my book on this topic: http://www.apeth.com/iOSBook/ch18.html#_gesture_recognizers