Ios – How to change the colour of the ‘Cancel’ button on the UISearchBar in Swift

iosswiftuisearchbar

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! 🙂

Best Answer

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)