iOS
UITextField
UIProgramming
KeyboardDismissal
SwiftDevelopment

iOS - Dismiss keyboard when touching outside of UITextField

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

When developing iOS applications, managing the on-screen keyboard is a common task particularly with user forms. One frequent issue is ensuring that the keyboard gets dismissed when the user taps outside of a UITextField. Correctly handling this behavior improves the user experience by keeping the UI clean and ensuring the user isn't obscured from the content. Let's delve into how you can achieve this with a combination of Swift, UIKit techniques, and good coding practices.

Technical Explanation

Dismissing the Keyboard

To achieve this functionality, you need to intercept touch events and detect touches that occur outside of any text input fields. Here's a step-by-step guide to implement this logic in your iOS app:

Step 1: Subclass UIViewController

You can achieve this by creating a method in your view controller that dismisses the keyboard when a touch is detected outside of a UITextField.

swift
1import UIKit
2
3class YourViewController: UIViewController {
4
5    override func viewDidLoad() {
6        super.viewDidLoad()
7        // Set up tap gesture recognizer
8        let tap = UITapGestureRecognizer(target: self, action: #selector(dismissKeyboard))
9        view.addGestureRecognizer(tap)
10    }
11
12    @objc func dismissKeyboard() {
13        view.endEditing(true)
14    }
15}

Step 2: Configure the Gesture Recognizer

  • Gesture Recognition: Set up a UITapGestureRecognizer attached to the view controller's view. This gesture recognizer will call a selector method when a tap is detected.
  • Selector Method: The method, dismissKeyboard, calls view.endEditing(true). This dismisses the keyboard for any active text field by ending the editing context.

Considerations

  • Interactive Elements: Ensure the gesture recognizer does not intercept touches needed for other interactive elements like buttons. Configure your recognizer with the property cancelsTouchesInView = false if required.
  • Multiple Text Fields: This solution is scalable across view controllers with multiple text fields, as the endEditing(true) method dismisses the keyboard regardless of which text field is active.

Example with Multiple TextFields

swift
1import UIKit
2
3class FormViewController: UIViewController, UITextFieldDelegate {
4
5    @IBOutlet weak var firstNameField: UITextField!
6    @IBOutlet weak var lastNameField: UITextField!
7
8    override func viewDidLoad() {
9        super.viewDidLoad()
10        
11        // Set delegate for text fields
12        firstNameField.delegate = self
13        lastNameField.delegate = self
14        
15        // Tap gesture recognizer
16        let tap = UITapGestureRecognizer(target: self, action: #selector(dismissKeyboard))
17        self.view.addGestureRecognizer(tap)
18    }
19
20    @objc func dismissKeyboard() {
21        self.view.endEditing(true)
22    }
23
24    // UITextFieldDelegate method
25    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
26        textField.resignFirstResponder()
27        return true
28    }
29}

Performance and Best Practices

  • Efficient Gesture Handling: Always ensure gesture recognizers are set appropriately to avoid unwanted side-effects, particularly in complex views with buttons and other controls.
  • Testing Across Devices: Verify the behavior on different device sizes, orientations, and in different contexts within your app to ensure consistent behavior.
  • Accessibility: Consider users who might employ alternative input means. Ensure that dismissing the keyboard does not adversely affect accessibility features.

Table of Key Points

FeatureDescription
Gesture RecognizerTap gesture to detect touches outside of UITextField.
Selector MethodCalls endEditing(true) to dismiss the current first responder.
UITextFieldDelegateUsed for additional control via methods like textFieldShouldReturn.
Handling Interactive ElementsConfigure recognizer to not interfere with other controls (e.g. set cancelsTouchesInView = false). Use shouldReceiveTouch to selectively handle touches.
Best PracticesTest on multiple devices Ensure no interference with other inputs

Additional Enhancements

  • Extensions: Consider writing extensions on UIViewController for reusability:
swift
1  extension UIViewController {
2      func setupKeyboardDismissRecognizer() {
3          let tap = UITapGestureRecognizer(target: self, action: #selector(dismissKeyboardOnTap))
4          view.addGestureRecognizer(tap)
5      }
6
7      @objc private func dismissKeyboardOnTap() {
8          view.endEditing(true)
9      }
10  }

By following this guide, you can implement a user-friendly solution for dismissing the keyboard when users tap outside a text field. This not only improves the application’s usability but also adheres to a good coding standard in iOS development.


Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.