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.
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
}
}
The Complete iOS App Development Bootcamp
Disclosure: This website may contain affiliate links, meaning when you click the links and make a purchase, we receive a commission.