On many Apple products when you type in a password incorrectly, the text field appears to “shake” back and forth as if telling you, “Nope. You entered a password incorrectly.” To create this shaking effect on a text field, you need to create an extension.
Extensions let you define new methods for manipulating an object. Since a text field is an object, created from the UITextField class, it’s possible to extend this UiTextField class with a custom shaking function.
To see how this works, create a Single View App iOS project and add a text field and a button on the user interface. Create an IBOutlet for the text field like this:
Then create an IBAction method for the button like this:
This simple project works by displaying a text field and a button. If you type a password correctly in the text field, then the text field displays the text “ACCESS GRANTED”. However, if you type an incorrect password, then the text field runs a shake function. To create this shake function, you need to create an extension at the bottom of the ViewController.swift file past the last curly bracket like this:
This shake function defines an animation that lasts 0.05 seconds, repeats itself 5 times, and moves the text field 4.0 pixels to the left and 4.0 pixels to the right, which creates the “shaking” visual effect.
Your complete ViewController.swift file should look like this:
When you run this app in the Simulator, type the word “password” in the text field and you’ll see the words “ACCESS GRANTED” in the text field. If you type anything other than “password” in the text field, the text field will shake back and forth.
By using extensions, you’ve extended the text field to make the shake() method available to the text field. Any time you want to modify a user interface item, use an extension to modify that object’s behavior.