Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tap Gesture Recognizer Interfering with Clear Button

I have a UITextField with the clear button enabled. I also have some code that dismisses the keyboard when the user taps anywhere else on the screen:

let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(dismissKeyboard))
tap.cancelsTouchesInView = false
view.addGestureRecognizer(tap)

func dismissKeyboard() {
    view.endEditing(true)
}

The problem is that this code interferes with the clear button, so the text field is never cleared. How do I prevent the tap gesture recognizer from handling the clear button tap?

like image 534
user2397282 Avatar asked Feb 22 '17 21:02

user2397282


1 Answers

Figured out a way to prevent this from happening.

So the clear button is of type UIButton, so we don't want the gesture recognizer to recognize those taps.

This function is called when the gesture recognizer receives a tap:

func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
    // Don't handle button taps
    return !(touch.view is UIButton)
}

The line:

return !(touch.view is UIButton)

Will return false if the place the user tapped was a UIButton and true otherwise.

So false = tap will not be handled by the gesture recognizer, and true = tap will be handled.

Don't forget to add the UIGestureRecognizerDelegate and set it using the following line:

tap.delegate = self
like image 149
user2397282 Avatar answered Nov 03 '22 21:11

user2397282