Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 379
Yi Li Avatar asked Nov 30 '22 08:11

Yi Li


2 Answers

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()
like image 131
anshul king Avatar answered Dec 09 '22 23:12

anshul king


Swift 4, 5. I always use hide keyboard when tapped around and return button.

override func viewDidLoad() {
    super.viewDidLoad()
    hideKeyboardWhenTappedAround()
    emailTextField.delegate = self // your UITextfield
    passwordTextField.delegate = self // your UITextfield
}

// Hide Keyboard

extension EmailAutorization: UITextFieldDelegate {

 // Return button tapped
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
    textField.resignFirstResponder()
    return true
}

// Around tapped
func hideKeyboardWhenTappedAround() {
    let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(EmailAutorization.dismissKeyboard))
    tap.cancelsTouchesInView = false
    view.addGestureRecognizer(tap)
}

@objc func dismissKeyboard() {
    view.endEditing(true)
}

}

like image 28
Evgeniy Avatar answered Dec 09 '22 23:12

Evgeniy