How do you dismiss the keyboard in SwiftUI?

← Swift answers

Bind the field to a @FocusState and set it to false or nil. For a scrolling form, add .scrollDismissesKeyboard(.interactively).

struct SearchView: View {
    @State private var query = ""
    @FocusState private var focused: Bool
 
    var body: some View {
        VStack {
            TextField("Search", text: $query)
                .focused($focused)
                .submitLabel(.search)
                .onSubmit { focused = false }
 
            Button("Done") { focused = false }
        }
        .contentShape(Rectangle())
        .onTapGesture { focused = false }
    }
}
ScrollView { /* fields */ }
    .scrollDismissesKeyboard(.interactively)

On iOS 14 and earlier, FocusState is not available. Use UIApplication.shared.sendAction(#selector(UIResponder.resignFirstResponder), to: nil, from: nil, for: nil) instead.

Related questions

Start debugging smarter today

Try Bugsee for free — no commitments, no hidden fees.

Free sign upLive demoNo credit card required