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
  • 82,064
  • 23
  • 174
  • 143
Li. Rui
  • 49
  • 11
  • 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

1

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
  • 13,571
  • 6
  • 76
  • 98
  • @ 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

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

Rohit Poudel
  • 1,793
  • 2
  • 20
  • 24
Nimish Raj
  • 13
  • 5
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