Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 467
Gaurang Avatar asked Sep 27 '13 10:09

Gaurang


3 Answers

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

like image 131
Toseef Khilji Avatar answered Nov 19 '22 14:11

Toseef Khilji


You can set the text colour by

[[UITextField appearanceWhenContainedIn:[UISearchBar class], nil] setTextColor:[UIColor blueColor]];
like image 95
SandeepM Avatar answered Nov 19 '22 15:11

SandeepM


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]}];
like image 35
Graham Dawson Avatar answered Nov 19 '22 14:11

Graham Dawson