Styling the cancel button in a UISearchBar

前端 未结 21 1399
-上瘾入骨i
-上瘾入骨i 2020-12-02 09:13

I have a UISearchBar that has a cancel button (it\'s displayed using -(void)setShowsCancelButton:animated). I\'ve changed the tintColor of the sear

21条回答
  •  庸人自扰
    2020-12-02 09:58

    Swift 2.1.1:

    There's no simple way to hook in and style the search bar, you need to grab the subview manually from the search bar and then apply your changes.

    var cancelButton: UIButton
    let topView: UIView = self.customSearchController.customSearchBar.subviews[0] as UIView
    for subView in topView.subviews {
     if subView.isKindOfClass(NSClassFromString("UINavigationButton")!) {
        cancelButton = subView as! UIButton
        cancelButton.enabled = true
        cancelButton.setTitle("TestTitle", forState: UIControlState.Normal) // Change to set the title
        cancelButton.setBackgroundImage(UIImage(named: "ImageName"), forState: .Normal) // Change this to set a custom cancel button image, set the title to "" to remove 'Cancel' text
       }
    }
    

提交回复
热议问题