Ctrl + Drag from the UItextfield in MainStoryboard to the ViewController Class and create a UITextField Outlet
After that select the UItextField again and Ctrl+drag in ViewController class but this time select Action connection and on storage select Did End On Exit then click connect.
in the action you just created type the name of your UItextField .resignFirstResponder()
@IBAction func textFieldResign(sender: AnyObject) {
yourTextFieldName.resignFirstResponder()
}
This will take care of hiding the keyboard when pressing the return key on keyboard.
Another example of hiding the keyboard when return key is pressed:
we add UITextFieldDelegate
protocol next to UIViewController
in the vieDidLoad function
we add self.yourTextFieldName.delegate = self
And Finally we add this
func textFieldShouldReturn(textField: UITextField) -> Bool {
yourTextFieldName.resignFirstResponder()
return true
}
The final code is this:
class ViewController: UIViewController, UITextFieldDelegate {
@IBOutlet var textField: UITextField!
func textFieldShouldReturn(textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?){
view.endEditing(true)
super.touchesBegan(touches, withEvent: event)
}
override func viewDidLoad() {
super.viewDidLoad()
self.textField.delegate = self
}
}
[textField resignFirstResponder];