Search code examples
iosswiftuitableviewuisearchbaruisearchcontroller

Change UISearchBar background image in iOS11


I want to change my UISearchBar background image. When adding it as the header view in my UITableView it works perfectly fine. However, when I want to change it for the SearchBar being set as the searchController of the navigationItem it won´t change the background image.

I´m using:

self.searchBar.searchBar.setBackgroundImage(UIImage(named: "#IMAGENAME")?.resizableImage(withCapInsets: UIEdgeInsets.zero, resizingMode: .stretch), for: .any, barMetrics: UIBarMetrics.default)

Does anybody know how to fix this issue?


Solution

  • You may be looking for this:

    if #available(iOS 11.0, *) {
        let sc = UISearchController(searchResultsController: nil)
        if let navigationbar = self.navigationController?.navigationBar {
            navigationbar.barTintColor = UIColor(patternImage: UIImage(named: "pattern")!)
        }
        navigationItem.searchController = sc
        navigationItem.hidesSearchBarWhenScrolling = false
    }
    

    Here is image:

    enter image description here

    And here is result:

    enter image description here

    Here is more detailed answer, if you want to change any other UI elements of search bar.