使用顔色生成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