NEW: Start my new Ultimate Portfolio App course with a free Hacking with Swift+ trial! >>

How to dismiss the keyboard for a TextField

Paul Hudson    @twostraws   

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()
            }
        }
    }
}

Subscribe to Hacking with Swift+

Sponsor Hacking with Swift and reach the world's largest Swift community!

Similar solutions…

BUY OUR BOOKS
Buy Pro Swift Buy Swift Design Patterns Buy Testing Swift Buy Hacking with iOS Buy Swift Coding Challenges Buy Swift on Sundays Volume One Buy Server-Side Swift (Vapor Edition) Buy Advanced iOS Volume One Buy Advanced iOS Volume Two Buy Advanced iOS Volume Three Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with macOS Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Server-Side Swift (Kitura Edition) Buy Beyond Code

Was this page useful? Let us know!

Average rating: 4.4/5

Link copied to your pasteboard.