# Dismiss the Keyboard Programmatically in SwiftUI

> Dismiss the iOS keyboard in SwiftUI using the @FocusState property wrapper to manage text field focus, with examples for form handlers and toolbar buttons

**URL:** https://sentry.io/answers/dismiss-keyboard-swiftui/

---

## The Problem

There are cases where we want to manually dismiss the iOS keyboard, either by tapping on a certain button, or after submitting a form. Tapping away from the focused element will not dismiss the keyboard by default.

## The Solution

Since iOS 15, SwiftUI provides the `@FocusState` property wrapper for managing text field focus. Setting the focus state to `false` (or `nil` for an optional enum) dismisses the keyboard declaratively.

### Using `@FocusState` with a Single Field

Bind a Boolean `@FocusState` to a text field using the `.focused()` modifier. Set it to `false` to dismiss the keyboard:

```swift
struct FormView: View {
    @State private var amount = ""
    @FocusState private var isAmountFocused: Bool

    var body: some View {
        VStack {
            TextField("Amount", text: $amount)
                .focused($isAmountFocused)

            Button("Submit") {
                isAmountFocused = false
            }
        }
    }
}
```

### Using `@FocusState` with Multiple Fields

When your form has multiple fields, use an optional enum so you can move focus between fields or dismiss the keyboard entirely by setting the value to `nil`:

```swift
struct CreateView: View {
    enum Field: Hashable {
        case amount, date, note
    }

    @State private var amount = ""
    @State private var note = ""
    @FocusState private var focusedField: Field?

    var body: some View {
        Form {
            TextField("Amount", text: $amount)
                .focused($focusedField, equals: .amount)
            TextField("Note", text: $note)
                .focused($focusedField, equals: .note)

            Button("Submit") {
                focusedField = nil
            }
        }
    }
}
```

### Adding a Keyboard Toolbar Dismiss Button

You can add a toolbar button above the keyboard that dismisses it on tap:

```swift
TextField("Amount", text: $amount)
    .focused($isAmountFocused)
    .toolbar {
        ToolbarItemGroup(placement: .keyboard) {
            Spacer()
            Button {
                isAmountFocused = false
            } label: {
                Label("Dismiss", systemImage: "keyboard.chevron.compact.down")
            }
        }
    }
```

### Legacy Approach (iOS 14 and Earlier)

If you need to support iOS 14, you can dismiss the keyboard by sending a `resignFirstResponder` action through UIKit:

```swift
import UIKit

func hideKeyboard() {
    UIApplication.shared.sendAction(#selector(UIResponder.resignFirstResponder), to: nil, from: nil, for: nil)
}
```

---

*Source: [sentry.io/answers/dismiss-keyboard-swiftui/](https://sentry.io/answers/dismiss-keyboard-swiftui/)*
