How To Detect Change In UITextField Swift

By Eddy Chung

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.

How To Detect UITextField Changes With Interface Builder

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.

add-row-info-plist_4

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.

connections-inspector

Drag the Editing Changed action into your Swift file.

connections-inspector_1

I’m going to name my IBAction textFieldChanged with the type UITextField:

textfieldChangedIBAction_1

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:

textfieldChangedIBAction_2

How To Detect UITextField Changes With Only Code

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.

If you liked this post, you'll love my free guide: Secrets To iOS Development. Speed up your learning curve - hundreds of students have already downloaded. Thanks for reading!
Profile Picture of Eddy Chung

Eddy Chung

I am a professional iOS developer in Silicon Valley. I teach iOS development on ZeroToAppStore.com. If you'd like to learn more about me click here or you can contact me at: eddy@zerotoappstore.com

Similar Posts