SwiftUI
keyboard management
iOS development
Swift programming
app UI design

How to hide keyboard when using SwiftUI?

Interview Questions practice on Codemia

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

Browse interview questions

Introduction

Developing applications using SwiftUI offers a modern approach by embracing declarative syntax. However, one common hurdle developers face is efficiently managing the software keyboard on touch devices. A frequent requirement is hiding the keyboard after typing is completed or when tapping outside the input field. This article explores various techniques and code examples demonstrating how to hide the keyboard when using SwiftUI.

Basic Understanding of UIKit and SwiftUI Integration

SwiftUI is designed to work seamlessly alongside UIKit. UIKit provides a simple method for hiding the keyboard by resigning the UIResponder. With SwiftUI, one can make the same effect achievable by utilizing several techniques to integrate with UIKit.

Techniques to Hide the Keyboard

1. Using @FocusState (Swift 5.5+)

SwiftUI from iOS 15 introduces the @FocusState property wrapper. By binding the focus state of your text fields, you can control their focus and subsequently manage the keyboard visibility.

Example:

swift
1import SwiftUI
2
3struct ContentView: View {
4    @FocusState private var textFieldIsFocused: Bool
5    @State private var text: String = ""
6
7    var body: some View {
8        VStack {
9            TextField("Enter text", text: $text)
10                .focused($textFieldIsFocused)
11                .textFieldStyle(.roundedBorder)
12                .padding()
13
14            Button("Dismiss Keyboard") {
15                textFieldIsFocused = false
16            }
17        }
18        .padding()
19    }
20}

2. Utilizing UIKit's Responder Chain

Another approach is to use a helper function that calls a UIKit method to dismiss the input view. This requires extending SwiftUI with UIKit capabilities.

Example:

A function to hide the keyboard using the UIResponder:

swift
1import UIKit
2
3extension UIApplication {
4    func endEditing(_ force: Bool) {
5        windows
6            .filter {$0.isKeyWindow}
7            .first?
8            .endEditing(force)
9    }
10}
11
12import SwiftUI
13
14struct ContentView: View {
15    @State private var text: String = ""
16    
17    var body: some View {
18        VStack {
19            TextField("Enter text", text: $text)
20                .textFieldStyle(RoundedBorderTextFieldStyle())
21                .padding()
22            
23            Button(action: {
24                UIApplication.shared.endEditing(true)
25            }) {
26                Text("Dismiss Keyboard")
27            }
28        }
29        .padding()
30    }
31}

3. Tap Gesture Recognition

You can add a gesture recognizer to the view hierarchy to detect taps outside of the TextField and dismiss the keyboard.

Example:

swift
1import SwiftUI
2
3struct ContentView: View {
4    @State private var text: String = ""
5
6    var body: some View {
7        VStack {
8            TextField("Enter text", text: $text)
9                .textFieldStyle(RoundedBorderTextFieldStyle())
10                .padding()
11
12            Spacer()
13        }
14        .contentShape(Rectangle())
15        .onTapGesture {
16            UIApplication.shared.endEditing(true)
17        }
18        .padding()
19    }
20}

Summary Table of Methods

MethodTechniqueSupported Platforms
@FocusStateUtilizes Swift 5.5's native state focus management.iOS 15+
UIResponder ExtensionAdds a UIKit extension for resigning the First Responder.iOS 13+
Tap GestureDetects taps outside of input to resign the First Responder.iOS 13+

Additional Considerations

  • Using Combine Framework:
    Developers can leverage the Combine framework to reactively manage keyboard presentation. Binding publishers with text field states can assist developers in triggering certain actions upon keyboard dismissal.
  • Optimization and Performance:
    When dealing with UITextFields or any UI components overlapping with visual views, optimizing views using onAppear and onDisappear methods for managing keyboard notifications can greatly enhance performance.
  • Multi-keyboard Management:
    In scenarios with multiple input fields, managing separate focus states for each field with a shared focus controller can help streamline the process.

Conclusion

Managing the keyboard is a universal requirement in mobile applications, and SwiftUI offers multiple approaches to achieving this goal. While SwiftUI continues to evolve, understanding how to seamlessly integrate with UIKit's robust capabilities remains vital. Whether utilizing @FocusState, UIKit’s UIResponder capabilities, or gesture recognitions, developers have a rich toolkit at their disposal to ensure seamless user experience in applications.


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.