How To Hide Keyboard In Swift On Pressing Return Key

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 and want to learn more, check out The Complete iOS Developer Bootcamp. Speed up your learning curve - hundreds of students have already joined. Thanks for reading!

Eddy Chung

I teach iOS development on ZeroToAppStore.com.

Similar Posts