Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 753
mfaani Avatar asked Oct 05 '16 17:10

mfaani


People also ask

How do you dismiss a keyboard from the tap?

Android devices have a solution; press the physical back button (provided on some mobile phones) or the soft key back button, and it closes the keyboard.

How do I hide the keyboard in Objective C?

In Objective-C:[[UIApplication sharedApplication] sendAction:@selector(resignFirstResponder) to:nil from:nil forEvent:nil]; This will resign the first responder (and dismiss the keyboard) every time, without you needing to send resignFirstResponder to the proper view. No matter what, this will dismiss the keyboard.

How do you make the keyboard disappear in Swift?

Via Tap Gesture This is the quickest way to implement keyboard dismissal. Just set a Tap gesture on the main View and hook that gesture with a function which calls view. endEditing .


2 Answers

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)
}
like image 175
Ahmad F Avatar answered Oct 11 '22 10:10

Ahmad F


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)
    }
}
like image 41
Pranav Wadhwa Avatar answered Oct 11 '22 09:10

Pranav Wadhwa