I have been in the hell of trying to customize UISearcBar
. The application i am working on supports iOS 11+ and so I decided to separate the customization process for above and below iOS 13. Here is the subclass of UISearchController
I am using;
class SearchController: UISearchController {
override func viewDidLoad() {
super.viewDidLoad()
DispatchQueue.main.async {
if #available(iOS 13.0, *) {
print()
self.searchBar.tintColor = .richBlueTwo
self.searchBar.barTintColor = .white
self.searchBar.searchTextField.backgroundColor = .richBlueTwo
self.searchBar.searchTextField.textColor = .white
} else {
self.searchBar.tintColor = .white
self.searchBar.barTintColor = .white
let searchTextField = self.searchBar.value(forKey: "searchField") as? UITextField
searchTextField?.textColor = .white
self.searchBar.setImage(UIImage(named: "iconSearch"), for: .search, state: .normal)
}
}
}
}
And the usage in a Controller
;
private var searchController = SearchController(searchResultsController: nil)
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.searchController = searchController
navigationItem.hidesSearchBarWhenScrolling = false
}
The problem I am facing is when initially the controller is loaded and appeared, these changes has been made does not have any affect in UI until UISearchBar
is activated. When there is tap or click on the search bar, colors and images are instantly changing to what they had been set.
Other weird thing is , initially status bar is lightContent
. Strangely, the following sequence keeps happening;
UISearchBar
is activated the first time. Status bar stays whiteUISearchBar
resignedFirstResponder(Cancel, clear buttons or tapped into the tableview). Status bar becomes black textUISearchBar
is activated again. Status bar becomes white again.Any guesses?
Try to make all this changes in the viewWillAppear
function.
*** EDIT:
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
view.addSubview(activityIndicator)
searchBar.tintColor = .darkGray
searchBar.placeholder = "Type movie title... "
searchBar.barTintColor = .black
navigationController?.navigationBar.barTintColor = .black
navigationController?.navigationBar.tintColor = .white
activityIndicator.hidesWhenStopped = true
activityIndicator.center = view.center
}