user3746428
user3746428

Reputation: 11175

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?

Upvotes: 5

Views: 3490

Answers (1)

Mr. Bean
Mr. Bean

Reputation: 4281

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

Upvotes: 12

Related Questions