Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iPhone UITextField background color

Tags:

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?

like image 237
Stephen Joy Avatar asked Dec 28 '09 21:12

Stephen Joy


People also ask

How to change TextField background color?

Steps to change TextField background color in FlutterStep 1: Locate the file where you have placed the TextField widget. Step 2: Inside the TextField widget, add the decoration parameter and assign the InputDecoration widget. Step 3: Inside the InputDecoration widget, add the filled parameter and set it to true .

How do I change TextField background color in Swiftui?

TextField view doesn't provide a way to add background color but we can use the background modifier to add color to the TextField.


2 Answers

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

like image 194
Peter Johnson Avatar answered Sep 27 '22 21:09

Peter Johnson


colored UITextField using overlay

The other answers don't have the shadows present on a UITextField with Rounded Rectangle style. After trying many options I finally just placed a UIView over the UITextField, with an identical frame and auto resize mask, set the alpha to 0.3, and set the background to a blue color. Then I used the snippet from Peter Johnson's answer to clip the rounded edges off the colored overlay view. Also, uncheck the 'User Interaction Enabled' checkbox in IB to allow touch events to cascade down to the UITextField underneath. Looks perfect now.

Side effect: your text will also be colorized (doesn't matter if it's black)

#import <QuartzCore/QuartzCore.h>  colorizeOverlayView.layer.cornerRadius = 6.0f; colorizeOverlayView.layer.masksToBounds = YES; 
like image 22
Jacob Jennings Avatar answered Sep 27 '22 19:09

Jacob Jennings