How can I change the UISearchBar search text color?
You have to access the UITextField
inside the UISearchBar. You can do that by using valueForKey("searchField")
var textFieldInsideSearchBar = yourSearchbar.valueForKey("searchField") as? UITextField
textFieldInsideSearchBar?.textColor = yourcolor
Swift 3 update
let textFieldInsideSearchBar = yourSearchbar.value(forKey: "searchField") as? UITextField
textFieldInsideSearchBar?.textColor = yourcolor
If you want to set text color for UISearchBar in storyboard (without code), it is easy to do as well (in identity inspector). Here is a red text for search bar.
If you only need to make it readable on a dark background you can change the barStyle. The following makes text and buttons in the searchbar white:
searchController.searchBar.barStyle = .black
Working in Swift 4 for me:
UITextField.appearance(whenContainedInInstancesOf: [UISearchBar.self]).defaultTextAttributes = [NSAttributedStringKey.foregroundColor.rawValue: UIColor.white]
Swift 4.2, IOS 12:
UITextField.appearance(whenContainedInInstancesOf: [UISearchBar.self]).defaultTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor.white]
public extension UISearchBar {
public func setTextColor(color: UIColor) {
let svs = subviews.flatMap { $0.subviews }
guard let tf = (svs.filter { $0 is UITextField }).first as? UITextField else { return }
tf.textColor = color
}
}