简体   繁体   中英

Set NavigationBar background to a solid color

Is there any way I can set the background of the Navigation Bar of the UINavigationController to a solid color?

I know I can change the Tint color, but that still leaves me with the gradient/glass effect.

Any way I can get rid of that, and just have a plain old solid color?

The following code also results in solid color of navigation bar:

[[UINavigationBar appearance] setBackgroundImage:[[UIImage alloc] init] forBarMetrics:UIBarMetricsDefault];
[[UINavigationBar appearance] setBackgroundColor:[UIColor redColor]];

I think you have to subclass UINavigationBar and override -(void)drawRect:(CGRect)rect :

UIColor *colorFlat = /* any UIColor*/
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetFillColorWithColor(context, [colorFlat CGColor]);
CGContextFillRect(context, rect);

I used to override drawRect method and fill color; but after iOS7 upgrade it causes some problems on UINavigationBar. If you write your own drawrect method, even if you call [super drawRect], it changes the bar's dimension and you end up with a navigationBar with 44 pixels height. The status bar is left empty.

To get a solid colored navigationBar, I used an image as background image (any small solid colored image will do since you are stretching it) and added this lines inside the initWithFrame method of the UINavigationBar subclass:

[self setBackgroundColor:[UIColor clearColor]]     
[[UINavigationBar appearance] setBackgroundImage:[[UIImage imageNamed:@"bgimage.png"] resizableImageWithCapInsets:UIEdgeInsetsMake(5, 5, 5, 5) resizingMode:UIImageResizingModeStretch] forBarMetrics:UIBarMetricsDefault]; 

The following code worked for me:

[self.navigationController.navigationBar setBackgroundImage:[UIImage new] forBarMetrics:UIBarMetricsDefault];
[self.navigationController.navigationBar setBarTintColor:[UIColor greenColor]];
self.navigationController.navigationBar.translucent = NO;
[self.navigationController.navigationBar setShadowImage:[UIImage new]];

Create a CustomUIViewController that extends UIViewController and override viewDidLoad to something like this:

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.view.backgroundColor = [UIColor colorWithRed: 0.0 green: 0.0 blue: 1.0 alpha: 1.0];
}

After that, use your CustomUIViewController in your controllers.

Credits

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