Search code examples
iosswiftswiftui

How do I make it possible for the user to dismiss a numerical keyboard in SwiftUI?


I have a TextField with numerical input:

TextField("Amount", text: amountRaw).keyboardType(.numberPad)

The only way I see how to dismiss this field is to move focus into a non-numeric field and then hit enter on that field. This is not ideal.

Isn't there a way to enable a dismiss keyboard button or something?

I've found people suggesting solutions like implementing click-outside to dismiss keyboard, but that's not really what I want since I want click into other text fields to work.


Solution

  • Putting together the answer from @rob-mayoff, @user24018863, and https://www.hackingwithswift.com/quick-start/swiftui/how-to-dismiss-the-keyboard-for-a-textfield I got a good solution:

    .scrollDismissesKeyboard(.interactively)
    

    On the containing view, this is nice to have. And then:

    TextField("money", value: $saveTarget, formatter: NumberFormatter())
    .keyboardType(.numberPad)
    .toolbar {
        ToolbarItemGroup(placement: .keyboard) {
            Spacer()
            Button("Done") {
            UIApplication.shared.sendAction(#selector(UIResponder.resignFirstResponder), to: nil, from: nil, for: nil)
            }
            .fontWeight(.bold)
        }
    }
    

    note that the .toolbar modification needs to be made on the top level view. If applied to many fields (like in a ForEach) you will get the toolbar button multiple times.