How to dismiss a keyboard on tap outside view in iOS swift

How to dismiss a keyboard on tap outside in iOS (swift) :

In this tutorial, we will learn how to dismiss a keyboard if the user taps on outside on any view. In iOS, the keyboard doesn’t dismiss automatically if the user taps anywhere outside of the keyboard view. So, we need to handle it manually. To achieve this, we can simply add one UITapGestureRecognizer to the parent view and dismiss the keyboard if any tap detected. The code looks like as below :

func setupKeyboardDismissRecognizer(){
        let tapRecognizer: UITapGestureRecognizer = UITapGestureRecognizer(
            target: self,
            action: #selector(ViewController.dismissKeyboard))
func dismissKeyboard()

Just call method setupKeyboardDismissRecognizer on viewDidLoad() method and that’s it. If any touch detected, it will call dismissKeyboard() method and it will close the keyboard.

Dismiss keyboard with a view with tableView :

Let’s take a look into the below image :

Screen Shot 2017 12 08 at 11 11 00 PM

Here, we have one tableView inside the viewController . If we will add the UITapGestureRecognizer on the parent view, the tap on tableView will not work if the keyboard is open. Because the touch event will first pass to the parent view and then it will call the dismissKeyboard . The touch event will not move to the child view of the parent view i.e. to the tableView. If you want to move the touch event to the tableview, i.e. tap on tableview will work even if the keyboard is open, you need to add the following line before adding the gesture recognizer.

tap.cancelsTouchesInView = false

Now, the touch event will move to all child views.