-
Notifications
You must be signed in to change notification settings - Fork 472
Registering for Text Field Events
Often, you will want to change or update elements in your app as the user types into a textField. Setting button states as well as updating other labels are common use cases for registering textField events.
Right-Click on the textField to access the Editing Changed event under, Sent Events. ctrl + drag from the little circle to the right of the event the Swift file associated with your ViewController. Name the action something that makes sense, like "editingChanged".
You have now created an action that will call your method, "editingChanged", each time the user edits text inside the textField.
In this example, we will check to see if either the username field or password field is empty and set the button state accordingly.
// create a conditional statement: if the username OR password fields are empty than...
if usernameField.text!.isEmpty || passwordField.text!.isEmpty {
// set the button state to disabled
loginButton.isEnabled = false
// otherwise
} else {
// set the button state to enabled
loginButton.isEnabled = true
}
}
In this use case example, we want the editingChanged()
method to be called when the user edits the username field as well as the password field. Thankfully, different events can share the same method. We can use the same technique of adding an action triggered by a textField event from step 1 of this guide, but this time, ctrl + drag right over your existing method until it is highlighted and release.