How To Hide Keyboard In Swift On Pressing Return Key

By Eddy Chung

If you have a UITextField and you want to hide the keyboard when the user is pressing the return key, use the textFieldShouldReturn function.

Here is the code example:

import UIKit

class ViewController: UIViewController {
    @IBOutlet weak var textField: UITextField!

    override func viewDidLoad() {
        super.viewDidLoad()
        textField.delegate = self // set delegate
    }
}

extension ViewController: UITextFieldDelegate {
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        textField.resignFirstResponder() // dismiss keyboard
        return true
    }
}

Be sure you have set the textField.delegate = self in your viewDidLoad() function.

Dismiss Keyboard When Clicking On Background

You may want to add another behavior, dismissing the keyboard when the user clicks off the UITextField.

To do this you can add a gesture recognizer to the background view:

class ViewController: UIViewController {
    @IBOutlet weak var textField: UITextField!

    override func viewDidLoad() {
        super.viewDidLoad()
        let tap = UITapGestureRecognizer(target: self, action: #selector(handleTap))
        view.addGestureRecognizer(tap) // Add gesture recognizer to background view
    }

    @objc func handleTap() {
        textField.resignFirstResponder() // dismiss keyoard
    }
}
If you liked this post, you'll love my free guide: Secrets To iOS Development. Speed up your learning curve - hundreds of students have already downloaded. Thanks for reading!
Profile Picture of Eddy Chung

Eddy Chung

I am a professional iOS developer in Silicon Valley. I teach iOS development on ZeroToAppStore.com. If you'd like to learn more about me click here or you can contact me at: eddy@zerotoappstore.com

Similar Posts