Honey Honey - 2 months ago 9
Swift Question

How to Dismiss keyboard when touching away across the entire app

I have multiple textFields in different viewControllers where keyboard is popped up.

I know how to dismiss keyboard when user clicks on a different part of the screen but I don't want to go and hard code it into every corner of my app.

So is there anyway to enforce keyboard getting keyboard dismissed everywhere on the app when the user clicks anywhere on the screen other than keyboard?

I was thinking of extending the UIViewController, but I also have some textFields inside a view that I add as a subview. Perhaps there could be someway that I extend TextField class itself?

Answer

I suggest to create a base UIViewController and let each of your ViewControllers inherit it; override touchesBegan method in it:

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

OR you can override viewDidLoad -in the base ViewController- and add a UITapGestureRecognizer to the view, as follows:

override func viewDidLoad() {
    let tapGesture = UITapGestureRecognizer(target: self, action: #selector(Base.endEditing))
    view.addGestureRecognizer(tapGesture)
}

func endEditing() {
    view.endEditing(true)
}