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
Swift 4.2
UIBarButtonItem.appearance(whenContainedInInstancesOf: [UISearchBar.self]).setTitleTextAttributes([NSAttributedString.Key.foregroundColor: UIColor.black], for: .normal)
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])
did you try UISearchBar.appearance().tintColor = UIColor.whiteColor()
The Swift 4.2 version, based on other answers:
let cancelButtonAttributes: [NSAttributedString.Key: Any] = [NSAttributedString.Key(rawValue: NSAttributedString.Key.foregroundColor.rawValue): UIColor.orange]
UIBarButtonItem.appearance(whenContainedInInstancesOf: [UISearchBar.self]).setTitleTextAttributes(cancelButtonAttributes, for: .normal)
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
I know this question does have enough answers but here is simple way to achieve, SearchBar Background colour and Cancel button background colour we can change directly it in storyboard Attributes inspector.
for SearchBar background colour
for SearchBar cancel button colour