Search code examples
uitextfielduisearchbarios10ios11uibackgroundcolor

UITextField backgroundColor in UISearchBar iOS 10+


I'm trying to set the background color of the text field in my search bar to a custom color. I looked at the answer here to no avail:

Cannot change search bar background color

See how that search bar has a red text field? I followed the code and can even verify that the UISearchBarTextField object was found and the background color of it is being set to UIColor.red, but the color does not change.

I've messed around with all the background colors of the superviews with hopes that it might help but I cannot get that color to change. Maybe there's some new trick or someone can shed some light on something that may be overriding the color somehow.

extension UISearchBar {
    var textField: UITextField? {
        return subviews.first?.subviews.first(where: { $0.isKind(of: UITextField.self) }) as? UITextField
    }
}

searchBar.textField?.backgroundColor = UIColor.red // <-- Not working
let textFieldInsideUISearchBarLabel = searchBar.textField?.value(forKey: "placeholderLabel") as? UILabel
textFieldInsideUISearchBarLabel?.textColor = UIColor.lightGray

Note that the text inside the UITextField object is changing to the lightGray like I want it, just not the UITextField background color.


Solution

  • After a long wait for an answer, I decided to try some experiments. I created a new project, dragged a search bar, connected it to the ViewController, added the UISearchBar extension, and set the color - exactly the same as I did in my main project.

    Voila! It does set the background color as it should, and as it shows in the linked topic in the main question.

    So, I put the projects side by side, opened the storyboard in each of them and started setting the properties of the searchBar, one at a time, until I could see why the bar is not being set like it should in the main project.

    The very first thing I tried was, search style. My project has it set to "Minimal". I changed it to "Minimal" in the test project and noticed right away that the color was no longer set.

    So, setting the "Search Style" property of the searchBar in the main project to "Default" allowed that background color to be set.

    I would appreciate it greatly if anyone could comment and say why it is that I can't use "Minimal" if I want to customize the background color, or how I could make it work.