Styling the cancel button in a UISearchBar

前端 未结 21 1421
-上瘾入骨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: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)
            }
        }
    
    }
    

提交回复
热议问题