Home Dismiss keyboard in iOS
Reply: 3

Dismiss keyboard in iOS

Okeano Published in 2017-11-14 18:55:26Z

I looked at and tried multiple solutions for Swift 3, Xcode 8 but couldn't get any to work. I've tried:

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {

and also setting a text field input as first responder:

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {            

I don't know if something from Xcode 8 to Xcode 9 that cause these methods to not work, or if I messed elsewhere. I have 9 text fields and they've all set delegate to self. Their tags are incremented to move on to the next text field on pressing return. Don't think that would affect it. Sorry, new at this! The code runs fine with either of those attempted functions, but they keyboard stays. I would just like to dismiss keyboard when touched outside of any text field.

anshul king
anshul king Reply to 2017-11-15 08:23:20Z

first of all write this extension in any swift file

extension UIViewController {
    func hideKeyboardWhenTappedAround() {
        let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(UIViewController.dismissKeyboard))


    func dismissKeyboard() {

Than in viewDidLoad of that View only call in any view controller there are textFields.

haarismuneer Reply to 2017-11-22 20:24:43Z

Are you sure that touchesBegan is being called? If you're sure, try adding self.resignFirstResponder() to your touchesBegan function. This tells your view controller that it's no longer the first responder and should dismiss the keyboard.

If not, what you'll want to do is create a UITapGestureRecognizer, add it to your view, and wire it to a function that calls self.resignFirstResponder().

R.Radev Reply to 2017-11-15 14:46:28Z

Did you tried to debug the program to see if the code stops in the function at all(with break point)? Usually this code should work...Check if those textFields are in the super view or in a child view and if they are maybe you should call self.childView.endEditing(true).

If you really work with multiple textFields maybe you should try IQKeyboardManager library. I use it in all my projects. You can find it here: https://github.com/hackiftekhar/IQKeyboardManager. Simple to use and with good support. Just install it trough cocoa pods, put IQKeyboardManager.sharedManager().enable = true in the AppDelegate and you're ready to go. :)

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.434406 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO