iosswiftuitextviewuitapgesturerecognizer

Add UITapGestureRecognizer to UITextView without blocking textView touches


How can I add a UITapGestureRecognizer to a UITextView but still have the touches getting through to the UITextView as normal?

Currently as soon as I add a custom gesture to my textView it blocks the tap for UITextView default actions like positioning the cursor.

var tapTerm:UITapGestureRecognizer = UITapGestureRecognizer()

override func viewDidLoad() {
    tapTerm = UITapGestureRecognizer(target: self, action: "tapTextView:")
    textView.addGestureRecognizer(tapTerm)
}

func tapTextView(sender:UITapGestureRecognizer) {
    println("tapped term – but blocking the tap for textView :-/")
…
}

How can I process taps but keep any textView behaviour like cursor positioning as is?


Solution

  • To do that make your view controller adopt to UIGestureRecognizerDelegate and override should recognize simultaneously with gesture recognizer method like:

    override func viewDidLoad() {
        tapTerm = UITapGestureRecognizer(target: self, action: "tapTextView:")
        tapTerm.delegate = self
        textView.addGestureRecognizer(tapTerm)
    }
    
    func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
        return true
    }