How to dismiss the keyboard for a TextField
How to dismiss the keyboard for a TextField êŽë š
Updated for Xcode 15
Updated in iOS 15
SwiftUI's TextField
will show the keyboard automatically when activated, but before iOS 15 it was tricky to hide the keyboard when you're done â particularly if you're using the keyboardType()
modifier with something like .numberPad
, .decimalPad
, or .phonePad
.
If you're supporting only iOS 15 and later, you can activate and dismiss the keyboard for a text field by focusing and unfocusing it. In its simplest form, this is done using the @FocusState
property wrapper and the focusable()
modifier â the first stores a Boolean that tracks whether the second is currently focused.
So, we could write a simple view that hides the keyboard when a button is tapped:
struct ContentView: View {
@State private var name = ""
@FocusState private var nameIsFocused: Bool
var body: some View {
VStack {
TextField("Enter your name", text: $name)
.focused($nameIsFocused)
Button("Submit") {
nameIsFocused = false
}
}
}
}
For more advanced uses, you can use @FocusState
to track an optional enum case that determines which form field is currently focused. For example, we might show three text fields asking the user for various pieces of information, then submit the form once the final piece has arrived:
struct ContentView: View {
enum Field {
case firstName
case lastName
case emailAddress
}
@State private var firstName = ""
@State private var lastName = ""
@State private var emailAddress = ""
@FocusState private var focusedField: Field?
var body: some View {
VStack {
TextField("Enter your first name", text: $firstName)
.focused($focusedField, equals: .firstName)
.textContentType(.givenName)
.submitLabel(.next)
TextField("Enter your last name", text: $lastName)
.focused($focusedField, equals: .lastName)
.textContentType(.familyName)
.submitLabel(.next)
TextField("Enter your email address", text: $emailAddress)
.focused($focusedField, equals: .emailAddress)
.textContentType(.emailAddress)
.submitLabel(.join)
}
.onSubmit {
switch focusedField {
case .firstName:
focusedField = .lastName
case .lastName:
focusedField = .emailAddress
default:
print("Creating accountâŠ")
}
}
}
}
Important
You should not attempt to use the same focus binding for two different form fields.
If you have to support iOS 14 and 13, things are trickier. In fact, I want to make one thing clear: there is no built-in way of doing this with SwiftUI in iOS 13 and 14 â there's no simple modifier we can attach, so if you were struggling to solve this it's not because you weren't trying hard enough.
To force SwiftUI to hide your keyboard, you need to use this code:
UIApplication.shared.sendAction(#selector(UIResponder.resignFirstResponder), to: nil, from: nil, for: nil)
Yes, that's very long, but it asks UIKit to search through what's called the responder chain â the collection of controls that are currently responding to user input â and find one that is capable of resigning its first responder status. That's a fancy way of saying âask whatever has control to stop using the keyboardâ, which in our case means the keyboard will be dismissed when a text field is active.
Because that code isn't particularly easy to read, you should consider wrapping it in an extension such as this:
#if canImport(UIKit)
extension View {
func hideKeyboard() {
UIApplication.shared.sendAction(#selector(UIResponder.resignFirstResponder), to: nil, from: nil, for: nil)
}
}
#endif
You can now write hideKeyboard()
from inside any SwiftUI view.
How you use that depends on your code, but here's a simple example that shows a decimal pad text field with a button to dismiss it:
struct ContentView: View {
@State private var tipAmount = ""
var body: some View {
VStack {
TextField("Tip Amount ", text: $tipAmount)
.textFieldStyle(.roundedBorder)
.keyboardType(.decimalPad)
Button("Submit") {
print("Tip: \(tipAmount)")
hideKeyboard()
}
}
}
}
#if canImport(UIKit)
extension View {
func hideKeyboard() {
UIApplication.shared.sendAction(#selector(UIResponder.resignFirstResponder), to: nil, from: nil, for: nil)
}
}
#endif
Important
If you're using Xcode 12 you need to use RoundedBorderTextFieldStyle()
rather than .roundedBorder
.