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

Base on Nick89's code , I changed like that for Swift 3.1

let cancelButtonAttributes: [String: AnyObject] = [NSForegroundColorAttributeName: UIColor.white]

UIBarButtonItem.appearance(whenContainedInInstancesOf: [UISearchBar.self]).setTitleTextAttributes(cancelButtonAttributes, for: .normal)

I want to change on UISearchBar only instead of all UIBarButton, so I'm using like UIBarButtonItem.appearance(whenContainedInInstancesOf: [UISearchBar.self])


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


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)