iPhone UITextField background color

Viewed 44415

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?

6 Answers

A dump of the view hierarchy reveals that the UITextField has a single subview of type UITextFieldRoundedRectBackgroundView, which in turn has 12 UIImageViews.

An older article by Erica Sadun shows an additional UILabel, which Apple apparently removed in later versions of the SDK.

Fiddling with the UIImageViews doesn't change much.

So the answer is: there's probably no way to change the background color.

When I encountered this problem, my approach was to set the background of my UITextField to clear and embed it within a larger UI View, which has the color and border that I desire. The following swift code does that. With this code, you can set the background color of the container view to whatever you want. For example, if you set the textContainer background color to yellow, it would look like this (though I wouldn't actually recommend this shade, it is just for example purposes):

enter image description here

If you show view frames in the Xcode debugger (image below) you see that the actual text field is a smaller rectangle inside what appears to be the text field (but is actually the container view). Note that Apple actually takes this same approach in the UIAlertController.

enter image description here

let field = UITextField()
field.font = UIFont.systemFont(ofSize: 13, weight: .regular)
field.backgroundColor = .clear

let textContainer = UIView()
textContainer.addSubview(field)
textContainer.isUserInteractionEnabled = true
textContainer.backgroundColor = .yellow
textContainer.layer.masksToBounds = true
textContainer.layer.borderWidth = 0.25
textContainer.layer.borderColor = myBorderColor
textContainer.layer.cornerRadius = 7.0
    
NSLayoutConstraint.activate([
    textContainer.heightAnchor.constraint(equalToConstant: 30.67),
    field.centerYAnchor.constraint(equalTo: textContainer.centerYAnchor),
    field.trailingAnchor.constraint(equalTo: textContainer.trailingAnchor, constant: -7.0),
    field.leadingAnchor.constraint(equalTo: textContainer.leadingAnchor, constant: 7.0),
 ])
Related