2

I am setting the barColor of my UISearchBar to the same color that my navigation bar is set to. When I get back the results in the UI the colors do not match. I have translucent set to YES for both the searchbar and the navigation bar.

enter image description here enter image description here

Can anyone tell me how I can get the color of the searchbar to match the nav bars color?

user3741418
  • 419
  • 1
  • 6
  • 12

3 Answers3

6

The easiest way I have found to accomplish this is by using an image instead of just a color.

[mySearchBar setBackgroundImage:[UIImage imageWithColor:[UIColor blackColor] forBarPosition:UIBarPositionAny barMetrics:UIBarMetricsDefault];

imageWithColor: is a category method I wrote on UIImage that looks like this:

+ (UIImage *) imageWithColor:(UIColor *)color
{
    CGRect rect = CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();

    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);

    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return image;
}

Doing this, I am able to get the UISearchBar background to match the UINavigationBar background exactly.

Dima
  • 23,484
  • 6
  • 56
  • 83
0

You can just set the backgroundColor of the UISearchBar to UIColor.clearColor(). Then the barTintColor will come through as you expect.

Micho
  • 3,929
  • 13
  • 37
  • 40
eito
  • 41
  • 2
0

I answered another SO question that is very similar to this one. Just setting translucent to NO won't do the trick. You have to slightly alter your color you use for the UISearchBar when you set it for the UINavigationBar. Check out my full answer here.

Community
  • 1
  • 1
Brandon A
  • 8,153
  • 3
  • 42
  • 77