Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change the colour of the 'Cancel' button on the UISearchBar in Swift

I have added a UISearchBar to the top of my PFQueryTableViewController. I have changed the colour of the searchBar to be the colour of my app, but in doing this, it seems to have also changed the colour of the 'Cancel' button to the right of it to the same colour. Ideally, I want the colour to be White.

This image shows how it currently looks:

It looks like there is no 'Cancel' button, but there is, its just the same colour as the searchBar (You can still press it etc)

Is there a way for me to change the colour of this 'Cancel button to white? Everything i've tried seems to make no difference.

Code i've used to make the UISearchBar this colour is:

UISearchBar.appearance().barTintColor = UIColor(hue: 359/360, saturation: 67/100, brightness: 71/100, alpha: 1) UISearchBar.appearance().tintColor = UIColor(hue: 359/360, saturation: 67/100, brightness: 71/100, alpha: 1) 

And in the storyboard i've set these:

enter image description here

And finally, to make the placeholder, and text white inside the SearchBar, i've used:

for subView in self.filmSearchBar.subviews {      for subsubView in subView.subviews {          if let searchBarTextField = subsubView as? UITextField {              searchBarTextField.attributedPlaceholder = NSAttributedString(string: NSLocalizedString("Search Cinevu film reviews", comment: ""), attributes: [NSForegroundColorAttributeName: UIColor.whiteColor()])              searchBarTextField.textColor = UIColor.whiteColor()          }      }  } 

Thanks for any help! :)

like image 563
Nick89 Avatar asked Feb 09 '16 21:02

Nick89


2 Answers

Having a look around, this seemed to be the best way to achieve what I needed:

 let cancelButtonAttributes = [NSAttributedStringKey.foregroundColor: UIColor.white]  UIBarButtonItem.appearance().setTitleTextAttributes(cancelButtonAttributes , for: .normal) 
like image 119
Nick89 Avatar answered Sep 25 '22 17:09

Nick89


Use this single line in code to change color of cancel button:

UIBarButtonItem.appearance(whenContainedInInstancesOf: [UISearchBar.self]).setTitleTextAttributes([NSAttributedStringKey(rawValue: NSAttributedStringKey.foregroundColor.rawValue): UIColor.white], for: .normal) 

Checked in Xcode 9.2 with Swift 4.0

like image 41
Incredible_Dev Avatar answered Sep 26 '22 17:09

Incredible_Dev