为搜索栏设置取消按钮文本颜色(Swift)

时间:2015-08-26 23:09:20

标签: ios swift uisearchbar

我正在尝试设置Swift中搜索栏旁边的“取消”按钮的文本颜色。这是我的代码:

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

它适用于突出显示的状态,但不适用于正常状态。我知道在Objective-C中我可以使用appearanceWhenContainedIn但是在Swift中不存在。

有什么想法吗?

1 个答案:

答案 0 :(得分: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)
        }
    }
}

它是UISearchBarDelegate的委托方法:)