UITapGestureRecognizer tap on self.view but ignore subviews

后端 未结 12 807
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-30 21:49

I need to implement a feature that will invoke some code when I double tap on the self.view (view of UIViewCotroller). But the problem that I have other UI obje

12条回答
  •  感情败类
    2020-11-30 22:17

    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 recognizer
    func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
         if touch.view?.isDescendant(of: tableView) == true {
            return false
         }
         return true
    }
    

提交回复
热议问题