Last Updated: January 28, 2019
·
2.289K
· saturngod

Change UINavigationBar background color

iOS 5 support appearance to change the UINavigationBar Design. However, we can't use UINavigationBar setBackgroundColor for changing color. We need to create image and use with setBackgroundImage:forBarMetrics: . So, I am using UIBezierPath to draw the background image instead of using png image.

-(UIImage*)barBackgroundImage{

    static UIImage *defaultImage = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        UIGraphicsBeginImageContextWithOptions(CGSizeMake(20, 44), NO, 0.0f);


        [[UIColor grayColor] setFill];
        [[UIBezierPath bezierPathWithRect:CGRectMake(0, 0, 20, 44)] fill];


        defaultImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();

    });

    return defaultImage;


}

-(void)setupUI
{
    [[UINavigationBar appearance] setBackgroundImage:[self barBackgroundImage] forBarMetrics:UIBarMetricsDefault];

}

4 Responses
Add your response

could you say also how to change barbuttons background?
i want the back and eventually left button to NOT show the border that defines the button, i would only show the "gliph" or the img... but i'm not figuring out how

to let you understand like facebook app, the dropped the buttons on the nav bar, they left just the "gliphs" :)

over 1 year ago ·

@zerho , use UIButton

UIButton* btn = [UIButton buttonWithType:UIButtonTypeCustom];
[btn setImage:[[self class] defaultImage] forState:UIControlStateNormal];

[btn setFrame:CGRectMake(0, 0, 22, 22)];
[btn addTarget:self action:@selector(toggleLeftPanel:) forControlEvents:UIControlEventTouchUpInside];

UIBarButtonItem* barBtn = [[UIBarButtonItem alloc] initWithCustomView:btn];
self.navigationItem.leftBarButtonItem = barBtn;
over 1 year ago ·

What about tint property, can't we use that to change the background color of navigation bar.

over 1 year ago ·

@amitibcmobile , tint color can change but it's not flat color.

over 1 year ago ·