Search code examples
swiftuikeyboardtextfieldios14

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


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


Solution

  • 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 = {})