Nathan C
Nathan C

Reputation: 286

How can I make the UISearchController SearchBar background color the true, untinted color?

I tried virtually every solution I could find for changing the background color of a UISearchController SearchBar, but none of them produced the correct color as the background. Every solution produces a somewhat darker color, and as demonstrated in the image below, white seems more pale / off-white.

How can I make the search bar a true white color?

One of the more recent "solutions" that results in white being pale is below:

let searchController = UISearchController()

override func viewDidLoad() {
    super.viewDidLoad()

    navigationItem.searchController = searchController

    let textFieldInsideSearchBar = searchController.searchBar.value(forKey: "searchField") as? UITextField
    textFieldInsideSearchBar?.backgroundColor = UIColor.white
}

enter image description here

Upvotes: 1

Views: 402

Answers (2)

r3to
r3to

Reputation: 1

I had a similar issue, where the backgroundColor of the UISearchBar appeared darker, than the expected. Using the view debugger, I noticed a semi transparent view, that is overlaying the view that has the backgroundColor I set. To work around that, here's the hacky solution I came up with:

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    let textField = searchController.searchBar.searchTextField
    textField.subviews.first?.subviews.first?.removeFromSuperview()
}

Upvotes: 0

griv
griv

Reputation: 2245

The default border style is being impacted by the navigationItem. If you remove the border style and manually set the corner radius, it should display as white. White seems to be the only color I ran into being affected by this.

Change:

 textFieldInsideSearchBar?.backgroundColor = UIColor.white

To:

 textFieldInsideSearchBar?.borderStyle = .none
 textFieldInsideSearchBar?.cornerRadius = 10
 textFieldInsideSearchBar?.backgroundColor = .white

When I put the search bar in a table header, your code above (without altering the border/radius) worked without issue, but when I tried to embed it into a navigation bar item, I ran into your problem.

Upvotes: 0

Related Questions