How to change the color of UINavigationBar?

2019-02-27 07:32发布

问题:

I want to change the color of UINavigationBar, color will be taken from an image.

回答1:

try to set the objects as subviews to the navigationBar.

Set the tint color property or use images

UINavigationController *controller = [[UINavigationController alloc] initWithRootViewController:rootController]; 
controller.navigationBar.tintColor = [UIColor blackColor];


回答2:

In iOS 7 or later, try the following:

navigationBar.barTintColor = [UIColor redColor];


回答3:

If you are supporting only iOS5 and later, you can use "appearance proxy". There is a good tutorial for this.

If you have to support prior versions, you have to subclass UINavigationBar and override its drawRect method. There is a good sample code for this.



回答4:

Try this:

  1. First create the Objective C class say CustomNavBar inherited UINavigationBar class...
  2. then import this class in your appDelegate...
  3. then Place this below code at the end of you appDelegate class...
  4. then open your MainWindow.xib and change the UINavigationBar class toCustomNavBar`.

The code:

@implementation CustomNavBar (CustomNavBarCategory)

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

    if([self isMemberOfClass:[CustomNavBar class]])
    {
        UIImage *image;

        image=[UIImage imageNamed:@"ImageName"];

        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.layer drawLayer:layer inContext:ctx];     
    }

}  

@end


回答5:

There is a way to do this from storyboard in xcode 6.4.

From the document outline select Navigation bar

Than from attribute inspector change bar tint

You can also pick other and this will bring the color picker

Pick the dropper and this will let you pick a color from an image