UITapGestureRecognizer tap on self.view but ignore subviews UITapGestureRecognizer tap on self.view but ignore subviews ios ios

UITapGestureRecognizer tap on self.view but ignore subviews


You should adopt the UIGestureRecognizerDelegate protocol inside the self object and call the below method for checking the view. Inside this method, check your view against touch.view and return the appropriate bool (Yes/No). Something like this:

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch{    if ([touch.view isDescendantOfView:yourSubView]) {        return NO;    }    return YES;}

Edit: Please, also check @Ian's answer!

Swift 5

// MARK: UIGestureRecognizerDelegate methods, You need to set the delegate of the recognizerfunc gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {     if touch.view?.isDescendant(of: tableView) == true {        return false     }     return true}


Another approach is to just compare if the view of the touch is the gestures view, because descendants won't pass the condition. A nice, simple one-liner:

func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {    return touch.view == gestureRecognizer.view}


And for the Swift variant:

func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldReceiveTouch touch: UITouch) -> Bool {    if touch.view.isDescendantOfView(yourSubView){        return false    }    return true}

Good to know, isDescendantOfView returns a Boolean value indicating whether the receiver is a subview of a given view or identical to that view.