Hiding Keyboard when tapped outside

When you are building iOS apps, you might have noticed that if you put some texts into TextFields, the emulator/phone keyboard doesn't disappear if you tap outside the keyboard automatically, like this:

Now if we want to hide the keyboard, it is very simple. Inside the ViewController of a Screen, add the following code in viewDidLoad() method:

override func viewDidLoad() {
    super.viewDidLoad()
    
    //MARK: recognizing the taps on the app screen, not the keyboard...
    let tapRecognizer = UITapGestureRecognizer(target: self, action: #selector(hideKeyboardOnTap))
    tapRecognizer.cancelsTouchesInView = false
    view.addGestureRecognizer(tapRecognizer)

}


//MARK: Hide Keyboard...
@objc func hideKeyboardOnTap(){
    //MARK: removing the keyboard from screen...
    view.endEditing(true)
}

Here, we create a gesture recognizer that recognizes that the user taps on the app screen. Then we add the recognizer to the view. Then we add the action (@objc func hideKeyboardOnTap()) for reacting to that gesture that would hide the keyboard. The end result is:

A great guide with other tricks can be found here: https://kaushalelsewhere.medium.com/how-to-dismiss-keyboard-in-a-view-controller-of-ios-3b1bfe973ad1

Last updated

Was this helpful?