简体   繁体   中英

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...

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 (ie 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]];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM