How to Dismiss keyboard when touching away across the entire app

梦想的初衷 提交于 2020-01-24 07:45:49

问题


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?


回答1:


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)
}



回答2:


You can also use an extension of a view controller, if you want the keyboard dismissal to apply to all of them:

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


来源:https://stackoverflow.com/questions/39880482/how-to-dismiss-keyboard-when-touching-away-across-the-entire-app

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!