iOS Week: Custom UITextFields

ezgif-1-28258ef67c.gif

Let’s see how we would make this text field in Swift

First create a UITextField subclass. I called mine UnderlinedTextField and annotated it as @IBDesignable. Now create a few properties.

Screen Shot 2018-03-27 at 15.55.30

These are annotated as @IBInspectable so they can be set in interface builder. We also need a property of hasError, which when set changes the colour of the text field:

Screen Shot 2018-03-27 at 15.56.35.png

When this property is set, we set the colour of our placeholderView. This is just a UILabel that we add and we animate it up when the user starts typing. Then if hasError is true, the text colour turns red and the view redraws to turn the underline colour to red. If it’s set again and is true again, the label will shake using a CAKeyframeAnimation.

Now we just override draw(_ rect: CGRect) and setup the placeholderView in didMoveToWindow(). That’s it, in about 100 lines of code. You can grab everything down below to look at in a bit more detail.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s