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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With