Is it possible to change the text color of the search bar? I don't seem to have access to the UISearchBarTextField class...
firstly, you find the subview in UISearchBar
, then find the UITextField
in sub View then change color
Try this code:-
for(UIView *subView in searchBar.subviews){
if([subView isKindOfClass:UITextField.class]){
[(UITextField*)subView setTextColor:[UIColor blueColor]];
}
}
for Ios 5 +
[[UITextField appearanceWhenContainedIn:[UISearchBar class], nil] setTextColor:[UIColor blueColor]];
As of iOS 5, the right way to do this is using the appearance protocol.
For example:
[[UITextField appearanceWhenContainedIn:[UISearchBar class], nil] setTextColor:[UIColor blueColor]];
You can set the attributes like so, call this in your controller.
[[UITextField appearanceWhenContainedIn:[self class], nil] setDefaultTextAttributes:@{NSForegroundColorAttributeName:[UIColor whiteColor], NSFontAttributeName:[UIFont systemFontOfSize:14]}];
*note that this will change all UITextFields in your controller
The original UISearchBar
hierarchy has changed since the original post and the UITextField
is no longer a direct subview. The below code makes no assumptions about the UISearchBar
hierarchy.
This is also useful when you don't want to change the search bar's text color throughout the entire application (i.e. using appearanceWhenContainedIn).
/**
* A recursive method which sets all UITextField text color within a view.
* Makes no assumptions about the original view's hierarchy.
*/
+(void) setAllTextFieldsWithin:(UIView*)view toColor:(UIColor*)color
{
for(UIView *subView in view.subviews)
{
if([subView isKindOfClass:UITextField.class])
{
[(UITextField*)subView setTextColor:color];
}
else
{
[self setAllTextFieldsWithin:subView toColor:color];
}
}
}
Usage:
[MyClass setAllTextFieldsWithin:self.mySearchBar toColor:[UIColor blueColor]];
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