UISearchBar text color change in iOS 7

How to change text color of UISearchBar in iOS 7?

In iOS 6, I was subclassing the UISearchBar and in layoutSubviews customising the properties of UITextField subview of UISearchBar.

But in iOS 7, UISearchBar doesn't have UITextField as its subview. How to fix this?


In iOS 7 to access Text Field you have to reiterate on level more. Change your code like this

for (UIView *subView in self.searchBar.subviews)
{
    for (UIView *secondLevelSubview in subView.subviews){
        if ([secondLevelSubview isKindOfClass:[UITextField class]])
        {
            UITextField *searchBarTextField = (UITextField *)secondLevelSubview;

            //set font color here
            searchBarTextField.textColor = [UIColor blackColor];

            break;
        }
    }
}

Note : This is Not Public API

OR

You can use appearance Property of UIControls, Like

[[UITextField appearanceWhenContainedIn:[UISearchBar class], nil] setDefaultTextAttributes:@{NSForegroundColorAttributeName:[UIColor redColor]}];

Note: Appearance proxy can be used for iOS 9.0+ OutPut

enter image description here

You can set The tintcolor to apply to key elements in the search bar.

Use tintColor to tint foreground elements.

Use barTintColor to tint the bar background.

In iOS v7.0, all subclasses of UIView derive their behavior for tintColor from the base class. See the discussion of tintColor at the UIView level for more information. Apple Doc


You can set the text colour by

[[UITextField appearanceWhenContainedIn:[UISearchBar class], nil] setTextColor:[UIColor blueColor]];

For XCode 6 (iOS8 SDK) the following DOESN'T work

[[UITextField appearanceWhenContainedIn:[UISearchBar class], nil] setTextColor:[UIColor redColor]];

But the following DOES work (for deployment to iOS7 and iOS8)

[[UITextField appearanceWhenContainedIn:[UISearchBar class], nil] setDefaultTextAttributes:@{NSForegroundColorAttributeName:[UIColor redColor]}];