Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change text color of search bar ios

Is it possible to change the text color of the search bar? I don't seem to have access to the UISearchBarTextField class...

like image 732
Renan Avatar asked May 23 '12 11:05

Renan


4 Answers

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]];
like image 170
Deepesh Avatar answered Oct 22 '22 13:10

Deepesh


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]];
like image 23
Tom Susel Avatar answered Oct 22 '22 13:10

Tom Susel


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

like image 31
mOp Avatar answered Oct 22 '22 14:10

mOp


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]];
like image 27
Jon Bryant Avatar answered Oct 22 '22 14:10

Jon Bryant