I had a very hard time figuring out how exactly to customize the search bar. Here's how I ended up doing things:
This code is in my AppDelegate class.
| UISearchBar.appearance().tintColor = UIColor(named: "Button") |
| |
| if let sky = UIColor(named: "Sky") |
| { |
| |
| UITextField.appearance(whenContainedInInstancesOf: [UISearchBar.self]).attributedPlaceholder = NSAttributedString(string: "Search", attributes: [NSAttributedStringKey.foregroundColor: sky]) |
| |
| |
| UITextField.appearance(whenContainedInInstancesOf: [UISearchBar.self]).defaultTextAttributes = [NSAttributedStringKey.foregroundColor.rawValue: sky] |
| |
| |
| UITextField.appearance(whenContainedInInstancesOf: [UISearchBar.self]).tintColor = sky |
| } |
| |
| |
| UISearchBar.appearance().setImage(UIImage(named: "clear"), for: .clear, state: .normal) |
This is an extension on UIView I'm using to help with the other search bar customizations.
| extension UIView |
| { |
| func getSubview<T>(type: T.Type) -> T? |
| { |
| let svs = subviews.flatMap { $0.subviews } |
| let element = (svs.filter { $0 is T }).first |
| |
| return element as? T |
| } |
| } |
And this is in the view controller.
| |
| if let textFieldInsideSearchBar = searchController.searchBar.getSubview(type: UITextField.self), let searchIconImageView = textFieldInsideSearchBar.leftView as? UIImageView |
| { |
| searchIconImageView.image = searchIconImageView.image?.withRenderingMode(UIImageRenderingMode.alwaysTemplate) |
| searchIconImageView.tintColor = UIColor.blue |
| } |
| |
| |
| if let textFieldInsideSearchBar = searchController.searchBar.getSubview(type: UITextField.self) |
| { |
| textFieldInsideSearchBar.layer.backgroundColor = UIColor.white.cgColor |
| |
| textFieldInsideSearchBar.layer.cornerRadius = 10.0 |
| } |