0
votes

I have a UIView object that I have added a UITapGestureRecognizer. The main view also has a UITapGestureRecognizer that i use to hide the keyboard. How can i prioritise the tapGesture on the child UIView to do what i need to do? I would like, when tapping the child view to trigger the action associated with this tap, rather than the main views's gesture.

I have tried adding a double tap to the child view, to distinguish between the two gestures, but this just triggers the action for the main views's tap action.

var childView: UIView!

 /**Tap screen event listener - to hide the keyboard*/
 let tapGesture = UITapGestureRecognizer.init(target: self, action: #selector(hideKeyBaord))
 self.view.addGestureRecognizer(tapGesture)


 let doubleTap = UITapGestureRecognizer.init(target: self, action: #selector(doSomethingElse))
 doubleTap.numberOfTouchesRequired = 2
 childView.view.addGestureRecognizer(doubleTap)
1
What do you mean by "prioritise"? Do you mean you don't want the main view's gesture recogniser to activate if the child view's gesture recogniser activates?Sweeper
@Sweeper yes pleasejamesMcKey

1 Answers

2
votes

One way is to implement the shouldReceiveTouch delegate method for tapGesture:

extension YourViewController : UIGestureRecognizerDelegate {
    override func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
        if gestureRecogniser == tapGesture {
            // tapGesture should not receive the touch when the touch is inside the child view
            let location = touch.location(in: childView)
            return !childView.bounds.contains(location)
        } else {
            return true
        }
    }
}

And remember to set the delegate of tapGesture to self.