3
votes

I trying to change Cancel button color in UISearchBar implemented with UISearchController (iOS 8 and greater). This is a code I use:

if self.resultSearchController.active {
        for subView in self.resultSearchController.searchBar.subviews  {
            for subsubView in subView.subviews  {
                if subsubView.isKindOfClass(UIButton) {
                    subsubView.tintColor =  UIColor.whiteColor()
                }
            }
        }
    }

If I paste it in viewDidLoad, it doesn't work, cause I think Cancel button initialize only when SearchController becomes Active.

If I paste code in viewDidLayoutSubviews everything work great, but I'm not sure its a correct way.

So, where I should put this code in TableViewController?

Also, I don't understand, how I can receive notification in my TableViewController that SearchController becomes inactive. In other words where I should put code like this:

if self.resultSearchController.active == false {
   //Do something 
}
3

3 Answers

1
votes

First you should insert delegate methods :-

 class HomeViewController: UIViewController,UISearchResultsUpdating, UISearchBarDelegate {

  var searchController: UISearchController!

  override func viewDidLoad() {
    super.viewDidLoad()
    searchController = UISearchController(searchResultsController: nil)
    searchController.searchResultsUpdater = self
    searchController.dimsBackgroundDuringPresentation = false
    searchController.searchBar.placeholder = "Search here..."
    searchController.searchBar.delegate = self
    searchController.searchBar.sizeToFit()
    searchController.hidesNavigationBarDuringPresentation = true
    tableView.tableHeaderView = searchController.searchBar
    searchController.searchBar.tintColor =  UIColor.whiteColor()

}

 func searchBarTextDidBeginEditing(searchBar: UISearchBar) {

}

func searchBarCancelButtonClicked(searchBar: UISearchBar) {

}

func searchBarSearchButtonClicked(searchBar: UISearchBar) {

}

func updateSearchResultsForSearchController(searchController: UISearchController) {

}


}

then used delegate methods and change cancel button colors and thing what you want

0
votes

You can try this in AppDelegate's didFinishLaunchWithOptions:.

UIBarButtonItem.appearanceWhenContainedInInstancesOfClasses([UISearchBar.self]).tintColor = UIColor.whiteColor()

PS: This is a generic method and would affect UIBarButtonItem in UISearchBar across app.

0
votes

Swift 4.2, 4.0+ An answer is added here for a custom search bar that can be customized as below,

enter image description here

You can check the usage of SearchBar class.