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.
