How to dismiss keyboard when touching anywhere outside UITextField (in swift)? How to dismiss keyboard when touching anywhere outside UITextField (in swift)? ios ios

How to dismiss keyboard when touching anywhere outside UITextField (in swift)?


Edited for Swift 4

Edit: Added @objc. While this isn't the best option for performance, one instance of it here shouldn't cause too many problems until there is a better solution.

Edited to fix when needing to interact with items behind GestureRecognizer.

Edit: Thanks @Rao for pointing this out. Added tap.cancelsTouchesInView = false.

This should help you with having multiple UITextView or UITextField

Create an extension of the view controller. This has worked much smoother for me and with less hassle than trying to use .resignFirstResponder()

extension UIViewController{    func setupToHideKeyboardOnTapOnView()    {        let tap: UITapGestureRecognizer = UITapGestureRecognizer(            target: self,            action: #selector(UIViewController.dismissKeyboard))        tap.cancelsTouchesInView = false        view.addGestureRecognizer(tap)    }    @objc func dismissKeyboard()    {        view.endEditing(true)    }}

Call self.setupToHideKeyboardOnTapOnView() in the viewDidLoad


Try this, it's tested and working:

For Swift 3.0 / 4.0

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {    self.view.endEditing(true)}

For Older Swift

override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent) {    self.view.endEditing(true)}


swift 3

override func viewDidLoad() {    super.viewDidLoad()    self.view.addGestureRecognizer(UITapGestureRecognizer(target: self.view, action: #selector(UIView.endEditing(_:))))}