Updated for Xcode 12.0
SwiftUI’s TextField
will show the keyboard automatically when activated, but it’s tricky to hide the keyboard when you’re done – particularly if you’re using the keyboardType()
modifier with something like .numberPad
, .decimalPad
, or .phonePad
.
I’m going to show you exactly how to hide the keyboard whenever you want in just a moment, but first I want to make one thing clear: there is no built-in way of doing this with SwiftUI – 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 self.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("Name: ", text: $tipAmount)
.textFieldStyle(RoundedBorderTextFieldStyle())
.keyboardType(.decimalPad)
Button("Submit") {
print("Tip: \(self.tipAmount)")
self.hideKeyboard()
}
}
}
}
SPONSORED Would you describe yourself as knowledgeable, but struggling when you have to come up with your own code? Fernando Olivares has a new book containing iOS rules you can immediately apply to your coding habits to see dramatic improvements, while also teaching applied programming fundamentals seen in refactored code from published apps.
Sponsor Hacking with Swift and reach the world's largest Swift community!
Link copied to your pasteboard.