textFieldDidBeginEditing and textFieldDidEndEditing in SwiftUI

Viewed 13402

how can I use the methods textFieldDidBeginEditing and textFieldDidEndEditing with the default TextField struct by apple.

3 Answers

TextField has onEditingChanged and onCommit callbacks.

For example:

@State var text = ""
@State var text2 = "default"
var body: some View {
    VStack {
        TextField($text, placeholder: nil, onEditingChanged: { (changed) in
            self.text2 = "Editing Changed"
        }) {
            self.text2 = "Editing Commited"
        }
        Text(text2)
    }
}

The code in onEditingChanged is only called when the user selects the textField, and onCommit is only called when return, done, etc. is tapped.

Edit: When the user changes from one TextField to another, the previously selected TextField's onEditingChanged is called once, with changed (the parameter) equaling false, and the just-selected TextField's onEditingChanged is also called, but with the parameter equaling true. The onCommit callback is not called for the previously selected TextField.

Edit 2: Adding an example for if you want to call a function committed() when a user taps return or changes TextField, and changed() when the user taps the TextField:

@State var text = ""
var body: some View {
    VStack {
        TextField($text, placeholder: nil, onEditingChanged: { (changed) in
           if changed {
               self.changed()
           } else {
               self.committed()
           }
        }) {
            self.committed()
        }
    }
}

SwiftUI 3 (iOS 15+)

Since TextField.init(_text:onEditingChanged:) is scheduled for deprecation in a future version it may be best to use @FocusState. This method also has the added benefit of knowing when the TextField is no longer the "first responder" which .onChange(of:) and .onSubmit(of:) alone will not do.

@State private var text = ""
@FocusState private var isTextFieldFocused: Bool
    
    var body: some View {
        TextField("Text Field", text: $text)
            .focused($isTextFieldFocused)
            .onChange(of: isTextFieldFocused) { isFocused in
                if isFocused {
                    // began editing...
                } else {
                    // ended editing...
                }
            }
    }

SwiftUI 2

ios15 and above

The syntax has changed for swiftui2 a modifier onChange is triggered when a property value has changed and onSubmit is triggered when form is submitted ie you press enter

TextField("search", text: $searchQuery)
    .onChange(of: searchQuery){ newValue in
         print("textChanged")
    }
    .onSubmit {
         print("textSubmitted")
    }
Related