FREE TRIAL: Accelerate your app development career with Hacking with Swift+! >>

How to dismiss the keyboard for a TextField

Paul Hudson    @twostraws   

Updated for Xcode 13.0

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

Download this as an Xcode project

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…")
            }
        }
    }
}

Download this as an Xcode project

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.

Hacking with Swift is sponsored by Essential Developer

SPONSORED Join a FREE crash course for iOS devs who want to become complete senior developers — from October 18th to 24th. Learn how to apply iOS app architecture patterns through a series of lectures and practical coding sessions.

Learn more

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.3/5

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.