I've read this page: Close iOS Keyboard by touching anywhere using Swift to find out how to hide keyboard, it's good when i touch on view, but when i touch on button it not work, does anyone know?
Asked
Active
Viewed 788 times
3 Answers
2
Paste this in your controller:
let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(YourViewController.dissmissKeyboard))
view.addGestureRecognizer(tap)
@objc func dissmissKeyboard() {
view.endEditing(true)
}

Federica Benacquista
- 835
- 11
- 25

Daniel Kuta
- 1,634
- 15
- 24
0
This is rather an hack, but it works pretty well and the keyboard even hides when tapped on background. I'm not sure if it works out for your problem with the button, but have a try!
EDIT: Try to add the UITapGestureRecognizer to your button?
in viewDidLoad add code:
self.hideKeyboardWhenTappedAround()
Then add an extension to your ViewController:
extension UIViewController {
func hideKeyboardWhenTappedAround() {
let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: "dismissKeyboard")
view.addGestureRecognizer(tap)
}
func dismissKeyboard() {
view.endEditing(true)
}
}
Works really well for me.

emmics
- 994
- 1
- 11
- 29
0
SWIFT 4
Add this to your viewDidLoad.
let endEditingTapGesture = UITapGestureRecognizer(target: view, action: #selector(UIView.endEditing(_:)))
endEditingTapGesture.cancelsTouchesInView = false
view.addGestureRecognizer(endEditingTapGesture)

Federica Benacquista
- 835
- 11
- 25