0

UISearchbar add navigationController?.navigationBar. How to change "Cancel" color

_searchBar = UISearchBar(frame: CGRect(frame: CGRect(x: 0, y: 0, width: 414, height: 64)))
_searchBar!.delegate = self
_searchBar!.showsCancelButton = true
backgroundColor = .white
barTintColor = .white
tintColor = .red
backgroundImage = UIImage()
_searchBar!.placeholder = "搜索文件"
navigationController?.navigationBar.addSubview(_searchBar!)

This result is "Cancel" color is white. How do I set it to red?

Anbu.Karthik
  • 80,161
  • 21
  • 166
  • 138
Li. Rui
  • 39
  • 8
  • see this once https://stackoverflow.com/questions/35302760/how-to-change-the-colour-of-the-cancel-button-on-the-uisearchbar-in-swift – Anbu.Karthik Aug 14 '17 at 05:57

3 Answers3

0

let cancelButtonAttributes: NSDictionary = [NSForegroundColorAttributeName: ``UIColor.YOUR COLOR] UIBarButtonItem.appearance().setTitleTextAttributes(cancelButtonAttributes as? [String : AnyObject], forState: UIControlState.Normal)

Rohit Poudel
  • 1,642
  • 2
  • 18
  • 20
Nimish Raj
  • 13
  • 5
0

Use appearance function of UIAppearance module -

Method 1:- Visible cancel button color when searchBar on load-

let attributes = [NSForegroundColorAttributeName : UIColor.red]
    UIBarButtonItem.appearance(whenContainedInInstancesOf: [UISearchBar.self]).setTitleTextAttributes(attributes, for: .normal)

or -

Method 2:- Visible cancel button color after searchBar clicked -

  UIBarButtonItem.appearance(whenContainedInInstancesOf:[UISearchBar.self]).tintColor = UIColor.red
Jack
  • 12,109
  • 4
  • 69
  • 95
  • @ Jack Thank you very much, it is work ,but it must iOS9.0 , @Anbu.Karthink answer applies to all system versions – Li. Rui Aug 14 '17 at 06:27
0

Changed the format to readability

let cancelButtonAttributes: NSDictionary = [NSForegroundColorAttributeName: UIColor.YOUR COLOR]     UIBarButtonItem.appearance().setTitleTextAttributes(cancelButtonAttributes as? [String : AnyObject], forState: UIControlState.Normal)
Nimish Raj
  • 13
  • 5