8

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?

user2397282
  • 3,798
  • 15
  • 48
  • 94
  • I'd have thought that gestures would follow *up* the view hierarchy but maybe not. You *can* detect if the button layer was tapped (maybe even the view but that might be at issue here. Once you know what's been tapped, you could direct the process flow properly. –  Feb 22 '17 at 21:50
  • Well if the user taps it what should happen? Should the button take priority or the gesture or both? If one is not firing call the IBAction manually and send the button as the sender – GregP Feb 22 '17 at 21:58
  • The button should take priority. And I also have another normal UIButton on the screen which should priority but it's always the gesture recognizer. – user2397282 Feb 22 '17 at 22:02

1 Answers1

10

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
user2397282
  • 3,798
  • 15
  • 48
  • 94