iPhone UITextField background color

Stephen Joy picture Stephen Joy · Dec 28, 2009 · Viewed 41.2k times · Source

I am unable to control the background color of a UITextField with a borderStyle= UITextBorderStyleRoundedRect. With this border style the backgroundColor property only seems to control a very narrow line along the inner edge of the rounded rectangle. The rest of the field remains white.

However, if the borderStyle is set to UIBorderStyle=UITextBorderStyleBezel then the entire background of the UITextField is controlled by its backgroundColor property.

Is this a feature? Is there a way to control the backgroundColor of a UITextField with a borderStyle=UITextBorderStyleRoundedRect?

Answer

Peter Johnson picture Peter Johnson · Nov 19, 2010

To change the background color in a UITextField you first need to use a different style of text field to the "rounded" style (such as the "no border" style) either in Interface Builder or programmatically.

You can then easily change the background colour with

textField.backgroundColor = backgroundColor;

where textField is your UITextField, and backgroundColor is a UIColor.

As a further tip- if you wish to restore the rounded corners appearance, you will first need to

#import <QuartzCore/QuartzCore.h>

and then set

textField.layer.cornerRadius=8.0f;
textField.layer.masksToBounds=YES

for this feature to work