UISearchBar cancel button color?

前端 未结 11 523
耶瑟儿~
耶瑟儿~ 2020-12-13 09:00

When I drop a UISearchBar into my view inside Interface Builder, and change its style to Black Opaque, the cancel button stays unfittingly blue / gray and doesn\'t become bl

相关标签:
11条回答
  • 2020-12-13 09:21

    for iOS 10:

    UISearchBar.appearance().tintColor = UIColor.red //cancel button color
    UISearchBar.appearance().barTintColor = UIColor.blue //background button color
    
    0 讨论(0)
  • 2020-12-13 09:24
    let view: UIView = self.searchBar.subviews[0] as UIView
    let subViewsArray = view.subviews
    
    for subView: UIView in subViewsArray {
        if let cancelButt = subView as? UIButton{
            cancelButt.setTitleColor(UIColor.white, for: .normal)         
        }
    }
    

    This worked for me

    0 讨论(0)
  • 2020-12-13 09:30

    In Swift 4.2

    let appearance = UIBarButtonItem.appearance(whenContainedInInstancesOf: [UISearchBar.self])
    appearance.setTitleTextAttributes([NSAttributedString.Key.foregroundColor: UIColor(named: "goldColor")!], for: .normal)
    

    This works for me. Thanks @Tim Semple

    0 讨论(0)
  • 2020-12-13 09:30

    I have taken Benjamin's answer and combined it with safe Array lookup to produce a short, but safe functional version:

    searchController.searchBar.tintColor = UIColor.whiteColor()
    (searchController.searchBar.subviews[safe: 0]?.subviews as? [UIView])?
        .filter({$0.isKindOfClass(UITextField)})
        .map({$0.tintColor = .lightGrayColor()})
    

    This results in coloring the Cancel button white and the cursor when typing gray. Otherwise it would be white and thus not seen. The searchController is an object of type UISearchController. If anybody wants to use it inside the results controller, replace it with self.

    The implementation of the safe: subscript is nkukushkin's answer:

    extension Array {
        subscript(safe index: Int) -> T? {
            return indices(self) ~= index ? self[index] : nil
        }
    }
    
    0 讨论(0)
  • 2020-12-13 09:30

    Click on Search bar and set the tint color under view from Interface Builder.

    0 讨论(0)
  • 2020-12-13 09:33

    For those looking to reproduce the same behavior in Swift :

    override func viewWillAppear(animated: Bool) {
        self.searchBar.tintColor = UIColor.whiteColor()
    
        let view: UIView = self.searchBar.subviews[0] as! UIView
        let subViewsArray = view.subviews
    
        for (subView: UIView) in subViewsArray as! [UIView] {
            println(subView)
            if subView.isKindOfClass(UITextField){
                subView.tintColor = UIColor.blueColor()
            }
        }
    
    }
    
    0 讨论(0)
提交回复
热议问题