天天看点

修改UINavigationController 背景颜色

使用颜色生成UIImage实现设置背景颜色,这样导航栏就没有渐变。

[self.navigationController.navigationBar setBackgroundImage:[UIImage imageWithColor:color] forBarMetrics:UIBarMetricsDefault];

//根据颜色返回图片
+(UIImage*) imageWithColor:(UIColor*)color
{
    CGRect rect = CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return image;
}
           

使用类别来实现

UINavigationBar 分类
#import <Foundation/Foundation.h>


@interface UINavigationBar (CustomImage)

- (void)drawRect:(CGRect)rect;
@end

#import "UINavigationBarCategory.h"


@implementation UINavigationBar (CustomImage)  
- (void)drawRect:(CGRect)rect {  
    UIImage *image = [UIImage imageNamed: @"navBar_withoutTitle.png"];  //背景图片
    [image drawInRect:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)]; 
}  
@end