Fix: Hide Keyboard in SwiftUI TextField on Return or Tap Outside

Fix: Hide Keyboard in SwiftUI TextField on Return or Tap Outside

Written by

in

Quick answer: Use @FocusState with a toolbar Done button (iOS 15+) to dismiss on Return. For tap-outside dismissal, add a UITapGestureRecognizer to the key window (iOS 14+) or use UIApplication.shared.sendAction(#selector(UIResponder.resignFirstResponder), to: nil, from: nil, for: nil) on any tap gesture.

Why this happens

SwiftUI’s TextField and SecureField don’t expose a built-in way to dismiss the keyboard. Unlike UIKit’s UITextField, there’s no resignFirstResponder() call available directly on the view. The keyboard stays visible until the system decides to hide it—usually when another field becomes first responder or the view disappears.

Two common dismissal triggers are missing by default:

  1. Return key – The keyboard’s return button only calls the field’s onSubmit (or legacy onCommit) closure; it doesn’t automatically resign first responder.
  2. Tap outside – Taps on non-interactive areas of the screen don’t propagate to the field, so the keyboard remains up.

Both behaviors require a small bridge to UIKit’s responder chain.

How to fix it

1. Dismiss on Return key – @FocusState + toolbar Done button (iOS 15+)

The modern, SwiftUI-native approach uses @FocusState to track which field is focused and a ToolbarItem(placement: .keyboard) to place a Done button above the keyboard.

struct LoginView: View {
    private enum Field: Hashable { case username, password }

    @State private var username = ""
    @State private var password = ""
    @FocusState private var focusedField: Field?

    var body: some View {
        NavigationStack {
            Form {
                TextField("Username", text: $username)
                    .focused($focusedField, equals: .username)
                    .submitLabel(.next)
                SecureField("Password", text: $password)
                    .focused($focusedField, equals: .password)
                    .submitLabel(.done)
            }
            .toolbar {
                ToolbarItemGroup(placement: .keyboard) {
                    Spacer()
                    Button("Done") { focusedField = nil }
                }
            }
            .onSubmit { 
                // Optional: move focus to next field
                if focusedField == .username { focusedField = .password }
                else { focusedField = nil }
            }
        }
    }
}

Why this works: Setting focusedField = nil tells SwiftUI to remove focus from all fields, which resigns first responder and hides the keyboard. The onSubmit handler lets you chain focus between fields before finally dismissing.

2. Dismiss on Return key – UIApplication.sendAction (iOS 14+)

If you need to support iOS 14 or prefer a one-liner without @FocusState, call the shared application’s sendAction:

extension UIApplication {
    func dismissKeyboard() {
        sendAction(#selector(UIResponder.resignFirstResponder),
                   to: nil, from: nil, for: nil)
    }
}

struct ContentView: View {
    @State private var name = ""

    var body: some View {
        TextField("Name", text: $name)
            .onSubmit { UIApplication.shared.dismissKeyboard() }
    }
}

This works on any iOS version that supports SwiftUI and doesn’t require a toolbar.

3. Dismiss on tap outside – window tap gesture (iOS 14+)

Add a tap gesture recognizer to the key window that calls endEditing(_:). Place this in your App entry point so it’s active for the entire app:

@main
struct MyApp: App {
    var body: some Scene {
        WindowGroup {
            ContentView()
                .onAppear { UIApplication.shared.addDismissKeyboardGesture() }
        }
    }
}

extension UIApplication {
    func addDismissKeyboardGesture() {
        guard let window = connectedScenes
            .compactMap({ ($0 as? UIWindowScene)?.keyWindow })
            .first else { return }

        let tap = UITapGestureRecognizer(target: window,
                                         action: #selector(UIView.endEditing))
        tap.requiresExclusiveTouchType = false
        tap.cancelsTouchesInView = false
        tap.delegate = self
        window.addGestureRecognizer(tap)
    }
}

extension UIApplication: UIGestureRecognizerDelegate {
    public func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer,
                                  shouldRecognizeSimultaneouslyWith other: UIGestureRecognizer) -> Bool {
        true // allow simultaneous gestures (scroll, drag, etc.)
    }
}

Key settings:
– cancelsTouchesInView = false – the tap still reaches buttons, links, and other controls.
– requiresExclusiveTouchType = false – doesn’t block multi-touch gestures.
– Delegate returns true for simultaneous recognition so scrolling a List or ScrollView still works.

4. Dismiss on tap outside – overlay tap gesture (per-view)

If you only need tap-outside dismissal on a specific screen, wrap the content in a Color.clear overlay with a tap gesture:

struct ContentView: View {
    @State private var name = ""

    var body: some View {
        Color.clear
            .contentShape(Rectangle())
            .onTapGesture { UIApplication.shared.dismissKeyboard() }
            .overlay(
                VStack {
                    Text("Hello \(name)")
                    TextField("Name", text: $name)
                        .textFieldStyle(.roundedBorder)
                        .padding()
                }
            )
    }
}

The contentShape(Rectangle()) makes the transparent color hit-testable. This avoids the App-level setup but only works where you apply it.

How to prevent it

  • Adopt @FocusState everywhere – It gives you programmatic control over focus and makes dismissal explicit.
  • Add the window tap gesture once at app launch – Covers every screen without per-view boilerplate.
  • Set appropriate submitLabel – Use .next, .done, .search, etc. so the Return key shows the right icon.
  • Test with external keyboards – Hardware keyboards don’t show the on-screen toolbar; onSubmit still fires.

FAQ

Does @FocusState work on macOS?

Yes. On macOS 12+, @FocusState controls focus between fields, but there’s no on-screen keyboard to dismiss. Setting the bound value to nil simply moves focus out of the field.

Why does the keyboard stay up when I push a new navigation view?

The field remains first responder until something else resigns it. Add .onDisappear { focusedField = nil } or call dismissKeyboard() before pushing.

Can I dismiss the keyboard from a button in a toolbar that’s not .keyboard placement?

Yes. Any button action that sets @FocusState to nil or calls UIApplication.shared.dismissKeyboard() will hide the keyboard, regardless of where the button lives.

Sources & credits

Parts of this guide are adapted from content licensed under CC BY-SA 4.0; this article is shared under the same license.