How to hide keyboard in swift on pressing return key? How to hide keyboard in swift on pressing return key? swift swift

How to hide keyboard in swift on pressing return key?


You can make the app dismiss the keyboard using the following function

func textFieldShouldReturn(_ textField: UITextField) -> Bool {    self.view.endEditing(true)    return false}

Here is a full example to better illustrate that:

////  ViewController.swift////import UIKitclass ViewController: UIViewController, UITextFieldDelegate {    @IBOutlet var myTextField : UITextField    override func viewDidLoad() {        super.viewDidLoad()        // Do any additional setup after loading the view, typically from a nib.        self.myTextField.delegate = self    }    func textFieldShouldReturn(_ textField: UITextField) -> Bool {        self.view.endEditing(true)        return false    }}

Code source: http://www.snip2code.com/Snippet/85930/swift-delegate-sample


The return true part of this only tells the text field whether or not it is allowed to return.
You have to manually tell the text field to dismiss the keyboard (or what ever its first responder is), and this is done with resignFirstResponder(), like so:

// Called on 'Return' pressed. Return false to ignore.func textFieldShouldReturn(_ textField: UITextField) -> Bool {     textField.resignFirstResponder()    return true}


Swift 4.2 - No Delegate Needed

You can create an action outlet from the UITextField for the "Primary Action Triggered" and resign first responder on the sender parameter passed in:

Create Action Outlet

@IBAction func done(_ sender: UITextField) {    sender.resignFirstResponder()}

Super simple.

(Thanks to Scott Smith's 60-second video for tipping me off about this: https://youtu.be/v6GrnVQy7iA)