Search code examples
iosswiftkeyboard

Dismiss keyboard in iOS


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?) {
    self.view.endEditing(true)         
}

and also setting a text field input as first responder:

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

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.


Solution

  • first of all write this extension in any swift file

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

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

    self.hideKeyboardWhenTappedAround()