Change ios search bar text color

Can I change the color of the text in the search bar? I don't seem to have access to the UISearchBarTextField class ...

+8
ios uisearchbar
source share
4 answers

firstly, you will find the preview in the UISearchBar , then find the UITextField in the preview, then change the 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]]; 
+19
source share

Like iOS 5, the right way to do this is to use the appearance protocol.

For example:

 [[UITextField appearanceWhenContainedIn:[UISearchBar class], nil] setTextColor:[UIColor blueColor]]; 
+11
source share

You can set such attributes, call it 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

+2
source share

The original UISearchBar hierarchy has changed since the original record and UITextField no longer a direct preview. In the code below, no assumptions are made about the UISearchBar hierarchy.

This is also useful if you do not want to change the color of the text of the search bar throughout the application (i.e. using appearanceWhenContainedIn ).

 /** * A recursive method which sets all UITextField text color within a view. * Makes no assumptions about the original view 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]; } } } 

Using:

 [MyClass setAllTextFieldsWithin:self.mySearchBar toColor:[UIColor blueColor]]; 
+2
source share

All Articles