Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set cancel button text colour for search bar (Swift)

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?

like image 938
user3746428 Avatar asked Aug 26 '15 23:08

user3746428


1 Answers

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

like image 196
Mr. Bean Avatar answered Oct 17 '22 10:10

Mr. Bean