Has anyone any idea or code sample on how can I change the text color of the placeholder text of a UISearchBar?
for iOS5+
use the appearance proxy
[[UILabel appearanceWhenContainedIn:[UISearchBar class], nil] setTextColor:[UIColor redColor]];
Found the answer from Change UITextField's placeholder text color programmatically
// Get the instance of the UITextField of the search bar
UITextField *searchField = [searchBar valueForKey:@"_searchField"];
// Change search bar text color
searchField.textColor = [UIColor redColor];
// Change the search bar placeholder text color
[searchField setValue:[UIColor blueColor] forKeyPath:@"_placeholderLabel.textColor"];
First solution is OK, but if you use multiple UISearchBar, or create a lot of instances it may fail. The one solution that always work for me is to use also appearance proxy but directly on UITextField
NSDictionary *placeholderAttributes = @{
NSForegroundColorAttributeName: [UIColor darkButtonColor],
NSFontAttributeName: [UIFont fontWithName:@"HelveticaNeue" size:15],
};
NSAttributedString *attributedPlaceholder = [[NSAttributedString alloc] initWithString:self.searchBar.placeholder
attributes:placeholderAttributes];
[[UITextField appearanceWhenContainedInInstancesOfClasses:@[[UISearchBar class]]] setAttributedPlaceholder:attributedPlaceholder];
Here is a Solution for Swift:
Swift 2
var textFieldInsideSearchBar = searchBar.valueForKey("searchField") as? UITextField
textFieldInsideSearchBar?.textColor = UIColor.whiteColor()
var textFieldInsideSearchBarLabel = textFieldInsideSearchBar!.valueForKey("placeholderLabel") as? UILabel
textFieldInsideSearchBarLabel?.textColor = UIColor.whiteColor()
Swift 3
let textFieldInsideSearchBar = searchBar.value(forKey: "searchField") as? UITextField
textFieldInsideSearchBar?.textColor = UIColor.white
let textFieldInsideSearchBarLabel = textFieldInsideSearchBar!.value(forKey: "placeholderLabel") as? UILabel
textFieldInsideSearchBarLabel?.textColor = UIColor.white
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With