Working with color and UINavigationItem's search controller

Working on an iOS 11 update that adopts the new large titles and embedded search controllers, but having some difficulty making the search bar appearance in the embedded controller legible.


Is there an official path for changing fill color or text color of UINavigationItem.searchController.searchBar? Existing API to customize the search bar seems to be incompatible. Slight edits to the fill color would be ideal, but I'm perfectly happy to settle on white text in the search bar.


Any insights are definitely appreciated!

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") // using this to set the text color of the 'Cancel' button since the search bar ignores the global tint color property for some reason
if let sky = UIColor(named: "Sky")
{
// Search bar placeholder text color
UITextField.appearance(whenContainedInInstancesOf: [UISearchBar.self]).attributedPlaceholder = NSAttributedString(string: "Search", attributes: [NSAttributedStringKey.foregroundColor: sky])
// Search bar text color
UITextField.appearance(whenContainedInInstancesOf: [UISearchBar.self]).defaultTextAttributes = [NSAttributedStringKey.foregroundColor.rawValue: sky]
// Insertion cursor color
UITextField.appearance(whenContainedInInstancesOf: [UISearchBar.self]).tintColor = sky
}
// Search bar clear icon
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.


// Changes the tint color of the magnifying glass icon, I'm calling it in ' viewDidAppear'
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
}
// Changes the background color of the search bar text field, I'm calling it in 'viewDidLoad'
if let textFieldInsideSearchBar = searchController.searchBar.getSubview(type: UITextField.self)
{
textFieldInsideSearchBar.layer.backgroundColor = UIColor.white.cgColor
textFieldInsideSearchBar.layer.cornerRadius = 10.0
}

You can also change the background color of the searchBar in iOS 11 this way:


https://stackoverflow.com/a/46315974/1109892

Working with color and UINavigationItem's search controller
 
 
Q