Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

textFieldDidBeginEditing and textFieldDidEndEditing in SwiftUI

Tags:

ios

swift

swiftui

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

like image 583
SwiftiSwift Avatar asked Jun 11 '19 19:06

SwiftiSwift


People also ask

How check TextField is empty or not in SwiftUI?

To check if the String value is empty I am going to use isEmpty that Swift provides. In the code example below I have two UITextFields which are called userNameTextField and userPasswordTextField. I first read the values that each UITextField contains and then check if these values are not empty.

How to use TextField in Swift UI?

A TextField is a type of control that shows an editable text interface. In SwiftUI, a TextField typically requires a placeholder text which acts similar to a hint, and a State variable that will accept the input from the user (which is usually a Text value).

How do I change TextField background color in SwiftUI?

TextField view doesn't provide a way to add background color but we can use the background modifier to add color to the TextField.


1 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()
        }
    }
}
like image 122
RPatel99 Avatar answered Oct 10 '22 19:10

RPatel99