UITapGestureRecognizer tap on self.view but ignore subviews

后端 未结 12 787
佛祖请我去吃肉
佛祖请我去吃肉 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:29

    If you don't want your 'double-tap recogniser' to conflict with your buttons and/or other controls, you can set self as UIGestureRecognizerDelegate and implement:

    func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool
    {
        return !(touch.view is UIControl)
    }
    
    0 讨论(0)
  • 2020-11-30 22:30

    Variant using CGPoint you touch (SWIFT 4.0)

    class MyViewController: UIViewController, UIGestureRecognizerDelegate {
    
      func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
    
    // Get the location in CGPoint
        let location = touch.location(in: nil)
    
    // Check if location is inside the view to avoid
        if viewToAvoid.frame.contains(location) {
            return false
        }
    
        return true
      }
    }
    
    0 讨论(0)
  • 2020-11-30 22:35

    Plus the above solutions, do not forget to check User Interaction Enabled of your sub-view.

    0 讨论(0)
  • 2020-11-30 22:39

    I had to prevent the gesture on the child view. The only thing that worked is to allow and keep the first view and prevent gesture in all the next views:

       var gestureView: UIView? = nil
    
        func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
            if (gestureView == nil || gestureView == touch.view){
                gestureView = touch.view
                return true
            }
            return false
         }
    
    0 讨论(0)
  • 2020-11-30 22:40

    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.

    0 讨论(0)
  • 2020-11-30 22:41

    Clear Swift way

    func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
        return touch.view == self.view
    }
    
    0 讨论(0)
提交回复
热议问题