views:

51

answers:

2

Hi,

is there an easy way to change the background color of the navigation item on top of a view? I have a navigation based app and I only want that one view gets another background color. I created the views mainly with IB. I found the following solution (not tested):

float r=10;
float g=55;
float b=130;
float a=0;

UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 120, 30)];
[label setBackgroundColor:[UIColor colorWithRed:r/255.f
                                          green:g/255.f
                                           blue:b/255.f    
                                          alpha:a/255.f];];
[self.navigationController.navigationBar.topItem setTitleView:label];
[label release];

Is there an easier way like

[navigationController.navigationBar setBackgroundColor:blueColor]

Or can I do it with IB (but without having the same color in every view)?

Many thanks in advance!

Cheers

A: 

You can use navigationController.navigationBar.tintColor;

Jerry Jones
+1  A: 

You could use:

[navigationController.navigationBar setTintColor:[UIColor redColor]; //Red as an example.

This would tint the color of the Navigation Bar and all it's Buttons to a specific color, in this case red. This property can also be set in Interface Builder.

And if you wanted to customize it further, you can set the background of the UINavigationBar to an image by sub-classing it. Like so…

Header File.

#import <UIKit/UIKit.h>

@interface UINavigationBar (CustomImage)

@end

Implementaion File.

#import "CustomNavigationBar.h"

@implementation UINavigationBar (CustomImage)

- (void)drawLayer:(CALayer *)layer inContext:(CGContextRef)ctx

{
    if([self isMemberOfClass: [UINavigationBar class]]){
        UIImage *image = [UIImage imageNamed:@"bar.png"];
        CGContextClip(ctx);
        CGContextTranslateCTM(ctx, 0, image.size.height);
        CGContextScaleCTM(ctx, 1.0, -1.0);
        CGContextDrawImage(ctx, CGRectMake(0, 0, self.frame.size.width, self.frame.size.height), image.CGImage);
    }else{
        [super drawLayer:layer inContext:ctx];
    }

}

@end

Then in Interface Builder set the class of you UINavigationBar to (in this case) CustomNavigationBar under the Identity Tab.

Joshua
Thanks! The first solution is currently sufficient enough. I used [[[self navigationController] navigationBar] setTintColor:[UIColor colorWithRed:255/255.f green:0/255.f blue:0/255.f alpha:0/255.f]];But the second one will be maybe in the productive version of my app ;)Still one question:In my other views I don't have an navigation Bar object in the nib. Is there an possibility to set the tint color in IB? Or is the only way to hardcode it?
testing
Unfortunately you can only set the tint color of the Navigation Bar in your main view in IB. If you want to change the tint between views you'll have to hardcode it.
Joshua
OK, that doesn't matter. I only wanted to know that. Thanks again!
testing