How do you hide the onscreen keyboard in iOS App?


To hide a keyboard on screen we need to make use of some internal functions that are predefined in the iOS SDK. The keyboard appears on screen when we are typing in a text Field or textView. We need to make use of internal function according to the text field.

For example if the current text field is tfOne, we can hide the text field using the code below:

tfOne.resignFirstResponder()

This code will hide the keyboard when ever called, we may call this on an action for a button or for gesture recognizer.

This method is good for limited textFields, but we need to make it better if we want to achieve the same with multiple textFields or textviews.

We can create a function for the same.

func hideKeyboardWhenTappedAround() {
   let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(UIViewController.dismissKeyboard))
   tap.cancelsTouchesInView = false
   view.addGestureRecognizer(tap)
}
@objc func dismissKeyboard() {
   view.endEditing(true)
}

We can use this function in our class and it will hide the keyboard whenever we tap on the screen outside any text field or text view.

But as you can see that it needs a view on which the gesture will be added, hence we need to embed this function into an UIViewExtension.

extension UIViewController {
   func hideKeyboardWhenTappedAround() {
      let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(UIViewController.dismissKeyboard))
      tap.cancelsTouchesInView = false
      view.addGestureRecognizer(tap)
   }
   @objc func dismissKeyboard() {
      view.endEditing(true)
   }
}

Now we can call this function in our viewDidLoad() and then whenever we tap anywhere in the view except a text View/ Field, the keyboard will be hidden.

Updated on: 30-Jul-2019

335 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements