I am trying to set the text colour of the Cancel button next to the search bar in Swift. This is the code I have:
func searchDisplayControllerWillBeginSearch(controller: UISearchDisplayController) {
self.searchDisplayController?.searchBar.showsCancelButton = true
var cancelButton: UIButton
var topView: UIView = self.searchDisplayController?.searchBar.subviews[0] as! UIView
for subView in topView.subviews {
if subView.isKindOfClass(NSClassFromString("UINavigationButton")) {
cancelButton = subView as! UIButton
cancelButton.setTitleColor(UIColorFromRGB(0x0096FF), forState: UIControlState.Selected)
cancelButton.setTitleColor(UIColorFromRGB(0x0096FF), forState: UIControlState.Normal)
}
}
}
It works for the highlighted state, but doesn't work for the normal state. I know in Objective-C I could use appearanceWhenContainedIn
but that doesn't exist in Swift.
Any ideas?
func searchBarTextDidBeginEditing(searchBar: UISearchBar) {
searchBar.setShowsCancelButton(true, animated: true)
for ob: UIView in ((searchBar.subviews[0] )).subviews {
if let z = ob as? UIButton {
let btn: UIButton = z
btn.setTitleColor(UIColor.blackColor(), forState: .Normal)
}
}
}
it is a delegate method of UISearchBarDelegate :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With