Add UITapGestureRecognizer to UITextView without blocking textView touches

Bernd picture Bernd · Mar 4, 2015 · Viewed 11.9k times · Source

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?

Answer

Zell B. picture Zell B. · Mar 4, 2015

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, shouldRecognizeSimultaneouslyWithGestureRecognizer otherGestureRecognizer: UIGestureRecognizer) -> Bool {

    return true
}