How to change inside background color of UISearchBar component on iOS

I know how to remove/change UISearchBar background color around search field:

[[self.searchBar.subviews objectAtIndex:0] removeFromSuperview];
self.searchBar.backgroundColor = [UIColor grayColor];

achieved UISearchBar customization

But don't know how to do this inside it like that:

desired UISearchBar customization

This needs to be compatible with iOS 4.3+.


Just customize the text field itself.

I am simply doing this and it works fine for me (iOS 7).

UITextField *txfSearchField = [_searchBar valueForKey:@"_searchField"];
txfSearchField.backgroundColor = [UIColor redColor];

This way you don't need to create an image, size it, etc...


Details

  • Xcode Version 11.0 (11A420a), swift 5

UISearchBar customising sample

Solution

import UIKit

extension UISearchBar {
    func getTextField() -> UITextField? { return value(forKey: "searchField") as? UITextField }
    func setTextField(color: UIColor) {
        guard let textField = getTextField() else { return }
        switch searchBarStyle {
        case .minimal:
            textField.layer.backgroundColor = color.cgColor
            textField.layer.cornerRadius = 6
        case .prominent, .default: textField.backgroundColor = color
        @unknown default: break
        }
    }
}

Usage

let searchBar = UISearchBar(frame: CGRect(x: 0, y: 20, width: UIScreen.main.bounds.width, height: 44))
//searchBar.searchBarStyle = .prominent
view.addSubview(searchBar)
searchBar.placeholder = "placeholder"
searchBar.setTextField(color: UIColor.green.withAlphaComponent(0.3))

Result 1

 searchBar.searchBarStyle = .prominent // or default

enter image description here

Result 2

 searchBar.searchBarStyle = .minimal

enter image description here

Full sample

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        let searchBar = UISearchBar(frame: CGRect(x: 0, y: 20, width: UIScreen.main.bounds.width, height: 44))
        //searchBar.searchBarStyle = .minimal
        searchBar.searchBarStyle = .prominent
        view.addSubview(searchBar)
        searchBar.placeholder = "placeholder"
        searchBar.setTextField(color: UIColor.green.withAlphaComponent(0.3))
    }
}