iOS UITextField How to dismiss the keyboard when user tap a retrun key.
Introduction
This article show you that how to dismiss the keyboard when user tap a return key on UITextField of iOS.
In fact, this way shows on the iOS SDK document. I've never knew it.
Solution
Adapt the UITextFieldDelegate on your ViewController
Assign the self in the textField's delegate
Implement the textFieldShouldReturn: method
On textFieldShouldReturn: method, call the resignFirstResponder()
And return the value true or false
class ViewController: UIViewController, UITextFieldDelegate { @IBOutlet var textField : UITextField! override func viewDidLoad() { self.textField.delegate = self } func textFieldShouldReturn(textField: UITextField!) -> Bool { self.view.endEditing(true) return false } }
Detail
textFieldShouldReturn:
This textFieldShouldReturn: method is called when user tap the return button on the keyboard.
If you want to do its default behavior for the return button, you need to return true otherwise false.
In this case, to dismiss the keyboard, it wouldn't be a problem that which value is returned.
resignFirstResponder
First Responder means like a focus.
So, when this method call, the focus will resign from the UITextField's instance.
The keyboard will dismiss when the focus would out.