When I drop a UISearchBar into my view inside Interface Builder, and change its style to Black Opaque, the cancel button stays unfittingly blue / gray and doesn\'t become bl
for iOS 10:
UISearchBar.appearance().tintColor = UIColor.red //cancel button color
UISearchBar.appearance().barTintColor = UIColor.blue //background button color
let view: UIView = self.searchBar.subviews[0] as UIView
let subViewsArray = view.subviews
for subView: UIView in subViewsArray {
if let cancelButt = subView as? UIButton{
cancelButt.setTitleColor(UIColor.white, for: .normal)
}
}
This worked for me
In Swift 4.2
let appearance = UIBarButtonItem.appearance(whenContainedInInstancesOf: [UISearchBar.self])
appearance.setTitleTextAttributes([NSAttributedString.Key.foregroundColor: UIColor(named: "goldColor")!], for: .normal)
This works for me. Thanks @Tim Semple
I have taken Benjamin's answer and combined it with safe Array
lookup to produce a short, but safe functional version:
searchController.searchBar.tintColor = UIColor.whiteColor()
(searchController.searchBar.subviews[safe: 0]?.subviews as? [UIView])?
.filter({$0.isKindOfClass(UITextField)})
.map({$0.tintColor = .lightGrayColor()})
This results in coloring the Cancel button white and the cursor when typing gray. Otherwise it would be white and thus not seen. The searchController
is an object of type UISearchController
. If anybody wants to use it inside the results controller, replace it with self
.
The implementation of the safe:
subscript is nkukushkin's answer:
extension Array {
subscript(safe index: Int) -> T? {
return indices(self) ~= index ? self[index] : nil
}
}
Click on Search bar and set the tint color under view from Interface Builder.
For those looking to reproduce the same behavior in Swift :
override func viewWillAppear(animated: Bool) {
self.searchBar.tintColor = UIColor.whiteColor()
let view: UIView = self.searchBar.subviews[0] as! UIView
let subViewsArray = view.subviews
for (subView: UIView) in subViewsArray as! [UIView] {
println(subView)
if subView.isKindOfClass(UITextField){
subView.tintColor = UIColor.blueColor()
}
}
}