I'm using this code to hide the keyboard when the user taps anywhere on the screen outside of the TextView:
override func viewDidLoad() {
super.viewDidLoad()
//Looks for single or multiple taps.
let tap = UITapGestureRecognizer(target: self, action: #selector(UIInputViewController.dismissKeyboard))
tap.delegate = self
//Uncomment the line below if you want the tap not not interfere and cancel other interactions.
tap.cancelsTouchesInView = false
view.addGestureRecognizer(tap)
}
//Calls this function when the tap is recognized.
@objc func dismissKeyboard() {
//Causes the view (or one of its embedded text fields) to resign the first responder status.
view.endEditing(true)
}
public func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
if touch.view is UIButton {
return false
}
return true
}
The problem is I have a UIButton
in this view as well - when I tap on the button, the button's gesture recognizer function is not called. Instead, dismissKeyboard
is called. I already tried the suggestion of using tap.cancelsTouchesInView = false
as well as the shouldReceive
method, but neither of them work - in the shouldReceive
method, when I tap on the button, the class of touch.view
is UIView
.
Does anybody know how to allow the user to hide the keyboard when clicking anywhere on screen, but also allow button action handlers to execute?