Dismissing the Keyboard on Tap
Learn how to improve user experience in Swift by dismissing the keyboard when a user taps on any empty area of the view, using a UITapGestureRecognizer.
Note:
This tutorial covers a common UX pattern: allowing users to dismiss the keyboard by tapping outside of a text field.
Overview
When a user is entering data into TextFields, the keyboard can obscure other parts of the UI. A great user experience enhancement is to dismiss the keyboard when the user taps on a non-interactive part of the screen.
This can be easily achieved using a UITapGestureRecognizer. You can add a gesture recognizer to your main view and use an @objc function to close the keyboard.
Reference:
Implementation
The implementation is straightforward and can be done in just two steps within your UIViewController.
Step 1: Add a Tap Gesture Recognizer
In your viewDidLoad() method, create an instance of UITapGestureRecognizer and add it to the view. The recognizer is initialized with a target (self) and an action (a selector for the function to be called).
// In your UIViewController
override func viewDidLoad() {
super.viewDidLoad()
// 1. Create a gesture recognizer
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(hideKeyboard))
// 2. Add it to the view
view.addGestureRecognizer(tapGesture)
}
Step 2: Create the @objc Function
Next, create the function that will be called when the tap gesture is recognized. This function needs the @objc attribute because it's being called by the Objective-C runtime through the selector.
Inside this function, you simply call view.endEditing(true). This method resigns the first responder status for any view that has it, which in the case of a TextField causes the keyboard to be dismissed.
// In your UIViewController
@objc func hideKeyboard() {
view.endEditing(true)
}
That's it! With these two small pieces of code, you have implemented a much more intuitive user experience for text input in your app.
Note:
This technique works globally for the view controller it's implemented in. Any time the keyboard is visible, a tap anywhere on the view (that doesn't have its own tap action) will dismiss it.