skip to Main Content

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.

2

Answers


  1. Make sure your text field is inside a ScrollView or a Form or a List, and adorn that container with .scrollDismissesKeyboard(.interactively). This allows a swipe or drag downward to dismiss the keyboard.

    Login or Signup to reply.
  2. You can use the power of @FocusState

    import SwiftUI
    
    struct ContentView: View {
        
        enum FocusedField {
                case amount, name
            }
        
        @State private var amountRaw = ""
        @State private var name = ""
        @FocusState private var focusedField: FocusedField?
        
        var body: some View {
            VStack {
                TextField("Amount", text: $amountRaw)
                    .keyboardType(.numberPad)
                    .focused($focusedField, equals: .name)
                
                TextField("Name", text: $name)
                    .focused($focusedField, equals: .name)
            }
            .textFieldStyle(.roundedBorder)
            .padding()
        }
    }
    
    #Preview {
        ContentView()
    }
    

    FocusStateExample

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search