You might want to hide a keyboard by tapping in the background of a view. In fact you are extremely likely to want to do this at some point in creating
- You just need to know what the keyboard is, a view and iOS
Tap: A UITapGestureRecognizer allows you to detect when the user taps the screen
A gesture recognizer within the ViewController
We can add a gesture recognizer, and resignFirstResponder from each TextField (or other control)
The function needs to be an @objc func as the instance method needs to be exposed to Objective-C
This is called by adding the tag-gesture (which can be added in ViewDidLoad(), or another appropriate point):
We would need to have this in every appropriate ViewController, and add *.resignFirstResponder() for many controls on the page. We really need a reusable way of doing this.
A UIViewController extension
We can create an extension for UIViewController that allows this to be used in any ViewController.
I’ve called this file UIViewController — hideKeyboardOnBackgroundTouched.swift and placed it in a folder called extensions within my project.
This can then be called from within any ViewController with the following:
Why it matters
You know that person, who uses your App. They pay your salary, either directly or indirectly. By resigning the keyboard at the right time you allow the user to have a better experience.
This is certainly something that you want.
Make it happen.
A clap is gratefully received, a follow likewise: