Jacksonkr
Jacksonkr

Reputation: 32207

ios UITextField extension (subclass)

I have a sign in form with inputs that have a white background and a red background. Instead of manually changing the backgroundfor each UITextField that has an error, can I extend the UITextField and add some extra functionality to it or is there a better way?

Also, if I do a custom UITextField, is there a way do use that in Interface Builder?

Upvotes: 0

Views: 2262

Answers (1)

Nick Lockwood
Nick Lockwood

Reputation: 40995

Create a UITextField subclass that implements your features. Then in Interface Builder, whenever you drag a UITextField onto your view, set its class in the Inspector to your UITextField subclass instead.

You'll still be able to configure it in IB like a regular UITextField, and it won't look any different in IB, but when your app is run it will have your custom background color.

Remember, if you are subclassing a textfield to be used in Interface Builder, you'll need to implement the initWithCoder or awakeFromNib methods instead of the initWithFrame method, or your custom setup code won't be run when it's created by the nib.

Also, you won't be able to set any custom properties of your subclass in IB, so if you need a red text field and a blue textfield, you'll need to create two separate subclasses if you want to use them in IB without needing to set their properties in code.

UPDATE: It's no longer true that you can't set custom properties in IB. You can now use the User Defined Runtime Attributes panel in the Inspector.

Upvotes: 6

Related Questions