TextField "Intro" Tap on the keyboard SwiftUI (iOS 14)

Viewed 448

Did you ever try to handle the event when you press intro and the keyboard dismiss in SwiftUI using TextField?

TextField("type your name here", text: $yourName)

How can I know when user dismiss keyboard pressing 'intro' button?

Thank you so much!

enter image description here

2 Answers

After the TextField is declared, add a closure and fill it with this code: UIApplication.shared.keyWindow?.endEditing(true)

So altogether it looks like

TextField($yourText){
    UIApplication.shared.keyWindow?.endEditing(true)
}

It is explained in this video around the 8:00 mark.

https://www.youtube.com/watch?v=TfJ70vHABjs

You can use onCommit parameter from TextField. Here is an example:

TextField("type your name here", text: $yourName, onCommit: {
    print("return key pressed")
})

From the documentation:

/// [...]
///   - onCommit: An action to perform when the user performs an action
///     (for example, when the user presses the Return key) while the text
///     field has focus.
public init(_ titleKey: LocalizedStringKey, text: Binding<String>, onEditingChanged: @escaping (Bool) -> Void = { _ in }, onCommit: @escaping () -> Void = {})
Related