Styling the cancel button in a UISearchBar

前端 未结 21 1368
-上瘾入骨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 10:14
    extension UISearchBar {
    var cancelButton : UIButton? {
        let topView: UIView = self.subviews[0] as UIView
    
        if let pvtClass = NSClassFromString("UINavigationButton") {
            for v in topView.subviews {
                if v.isKind(of: pvtClass) {
                    return v as? UIButton
                }
            }
        }
    
        return nil
    }
    }
    
    0 讨论(0)
  • 2020-12-02 10:15

    Change the title of 'Cancel' button:

    [[UIButton appearanceWhenContainedIn:[UISearchBar class], nil] setTitle:@"newTitle" forState:UIControlStateNormal];
    

    Swift equivalent:

       let cancelButton = UIButton.appearance(whenContainedInInstancesOf: [UISearchBar.self])
       cancelButton?.setTitle("cancel".localized, for: .normal)
    
    0 讨论(0)
  • 2020-12-02 10:16

    First of all I'd like to thank @Eliott from this https://stackoverflow.com/a/37381821/1473144

    I had to make a few adjustments for his answer to work in my specs that go below. Please, I ask the OP to update the accepted answer as it's VERY outdated.

    Swift 3, iOS 10 & Xcode 8.2.1

    searchBar.showsCancelButton = true
    var cancelButton: UIButton
    let topView: UIView = self.searchBar.subviews[0] as UIView
    for subView in topView.subviews {
        if let pvtClass = NSClassFromString("UINavigationButton") {
            if subView.isKind(of: pvtClass) {
                cancelButton = subView as! UIButton
    
                cancelButton.setTitle("", for: .normal)
                cancelButton.tintColor = UIColor.black
                cancelButton.setImage(#imageLiteral(resourceName: "searchX"), for: .normal)
            }
        }
    
    }
    
    0 讨论(0)
提交回复
热议问题