iOS 11 UISearchBar background color

let searchBar = UISearchBar(frame: CGRect())
let searchField: UITextField? = searchBar.value(forKey: "searchField") as? UITextField
let searchBarBackground: UIView? = searchBar.value(forKey: "background") as? UIView
// searchBarBackground?.removeFromSuperview()

if searchField != nil {
    var frame = searchField?.frame
    frame?.size.height = 30
    searchField?.frame = frame!
    searchField?.backgroundColor = .yellow
}

searchBar.barTintColor = .red
searchBar.delegate = self
searchBar.backgroundColor = .green

Runtime Views Hierarchy

If we set background colors for UISearchBar with code above, we'll see the colored subviews as follow images(click links to see). 

backgroundColor for Superview of UISearchBar subviews

We can see the Class Name of green view is UISearchBar in Object inspector.

So, if we use searchBar.backgroundColor = .green, we'll set the backgroundColor of Superview green. Therefore, the UISearchBar instance property backgroundColor will set the superview's background color.

Superview of UISearchBar

barTintColor for UISearchBarBackground

We can see the Class Name of red view is UISearchBarBackground in Object inspector.

However, there's no direct method to access the view, we can use KVC searchBar.value(forKey: "background") as? UIView try to get searchBarBackground.

If we use searchBar.barTintColor = .red, we'll set the backgroundColor of UISearchBarBackground's view red. In order to remove two black border on the tint bar layer, we have to remove the background from superview.

barTintColor of UISearchBar

searchField?.backgroundColor for UITextField

We can see the Class Name of yellow view is _UISearchBarSearchFieldBackgroundView (Subview of UISearchBarTextField) in Object inspector.

There's no direct method to access the searchField, same as searchBarBackground. We can also use KVC searchField: UITextField? = searchBar.value(forKey: "searchField") as? UITextField try to get searchField.

If we use searchField?.backgroundColor = .yellow, we'll set the backgroundColor of UITextField yellow. Therefore, if we want to set text field background color, we have to access the searchField with KVC first

UITextField of UISearchBar


I think you may be looking for this, right? But I've it in Swift :(

@IBOutlet weak var sbSearchBar: UISearchBar!

if let textfield = sbSearchBar.value(forKey: "searchField") as? UITextField {
    textfield.textColor = UIColor.blue
    textfield.backgroundColor = UIColor.yellow
}

Here is result:

enter image description here


This Swift code changes the background color of the text field:

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        
    // background color of text field
    UITextField.appearance(whenContainedInInstancesOf: [UISearchBar.self]).backgroundColor = .cyan        
}

This is the result

example used to change the background to cyan color