ios5uinavigationbarcustomizing

UINavigationBar with solid color iOS 5


I'm using the category to customize nav bar. My code is:

- (void) drawRect:(CGRect)rect {
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColor(context, CGColorGetComponents([self.tintColor CGColor]));
    CGContextFillRect(context, rect);
}

It works well, but not in iOS 5. I need nav bar color to be solid without any gradient. How should I do this?

As I know, for iOS 5 the only way to replace drawRect method is to make a subclass, but is there any way to make all navigation controllers to use UINavigationBar subclass instead of original class?


Solution

  • In iOS 5 you can use the UIAppearance protocol to set the appearance of all UINavigationBars in your app. Reference: link.

    The way I got a solid color was to create a custom image for the navigation bar, and set it as UINavigationBars background. You might have to create the image with the same size as the UINavigationBar, at least that's what I did.

    In your app delegate, do something like this:

    UIImage *image = [UIImage imageNamed:@"navbarbg.png"];
    [[UINavigationBar appearance] setBackgroundImage:image forBarMetrics:UIBarMetricsDefault];
    

    You also have to add the UIAppearanceContainer protocol to the header file:

    @interface AppDelegate : UIResponder <UIApplicationDelegate, UIAppearanceContainer>
    
    @end
    

    You can probably achieve the same thing by setting some color or something, instead of an image. But I found this to be an easy solution.