5

I'm trying to set background color for a text field inside a search bar. At first I did this:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    [UITextField appearanceWhenContainedInInstancesOfClasses:@[[UISearchBar class]]].backgroundColor = [UIColor blueColor];

    return YES;
}

and it doesn't work. The color remains white. Ok. I got it working by calling this code:

UISearchBar* searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, 150, 44)];

self.tableView.tableHeaderView = searchBar;

[UITextField appearanceWhenContainedInInstancesOfClasses:@[[UISearchBar class]]].backgroundColor = [UIColor blueColor];

from viewDidLoad. But it works only once. When opening another view controller of this class the background color remains unchanged.

You can try it yourself. Just create a simple template iOS app and add UISearchBar. Then try to set background color for its text field via UIAppearance.

What's wrong? Is it an iOS bug? I know I can traverse through all the search bar's subviews, find UITextField and set its background color but I want to find out what's happening.

Andrey Chernukha
  • 21,488
  • 17
  • 97
  • 161
  • Something here may help you... https://stackoverflow.com/questions/13817330/how-to-change-inside-background-color-of-uisearchbar-component-on-ios – DonMag Jun 26 '18 at 18:59

0 Answers0