5

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?

user3746428
  • 11,047
  • 20
  • 81
  • 137
  • 1
    Have you tried this : http://stackoverflow.com/a/27807417/765298 ? – Losiowaty Aug 26 '15 at 23:17
  • "I know in Objective-C I could use appearanceWhenContainedIn but that doesn't exist in Swift." Actually, in Swift 2.0, it does exist. – matt Aug 26 '15 at 23:26
  • 1
    I'm not using 2.0 right now, but I used the technique @Losiowaty suggested and it works perfectly! Thanks. – user3746428 Aug 26 '15 at 23:31

1 Answers1

12
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 :)

Mr. Bean
  • 4,221
  • 1
  • 19
  • 34