Detecting when a user types in a UITextField is a common problem iOS developers face.
Fortunately it’s not too difficult to figure this out and in this tutorial I’ll show you how. We’ll use two methods, one involving the interface builder and another one in pure Swift code.
Open up your storyboard or .xib file. Then open up your ViewController.swift file in the assistant editor. You can do this by holding Option and clicking on the file. It should open your Swift file side by side to your storyboard.
Now select the UITextField in your storyboard that you want to monitor text changes too. Then open up the connections inspector - you can use the keyboard shortcut CMD+Option+6 or select it from the right-hand pane.
Drag the Editing Changed
action into your Swift file.
I’m going to name my IBAction textFieldChanged
with the type UITextField
:
Inside this function, you can write whatever code you desire. For the purposes of this tutorial, we’re simply going to write a print statement.
@IBAction func textFieldChanged(_ sender: UITextField) {
print(sender.text)
}
This will simply print the current text in the text field every time the user edits the text field. Go ahead and run your application. This is what your console should print when you type into the textfield:
What about if you’re not using the interface builder? How do you detect changes in the UITextField?
Add a target to the UITextField
for the control event editingChanged
:
textField.addTarget(self, action: "textFieldDidChange:", forControlEvents: UIControlEvents.EditingChanged)
Now implement the textFieldDidChange
function like before, but be sure to prefix the function with @objc
. Not doing this may lead to a crash.
@objc func textFieldDidChange() {
print(textfield.text)
}
Run your application and you should see the text printed into console as you change it.
The Complete iOS App Development Bootcamp
Disclosure: This website may contain affiliate links, meaning when you click the links and make a purchase, we receive a commission.