Ios5 带纯色iOS 5的UINavigationBar

Ios5 带纯色iOS 5的UINavigationBar,ios5,uinavigationbar,customizing,Ios5,Uinavigationbar,Customizing,我正在使用类别自定义导航栏。我的代码是: - (void) drawRect:(CGRect)rect { CGContextRef context = UIGraphicsGetCurrentContext(); CGContextSetFillColor(context, CGColorGetComponents([self.tintColor CGColor])); CGContextFillRect(context, rect); } 它运行良好,但在iOS 5

我正在使用类别自定义导航栏。我的代码是:

- (void) drawRect:(CGRect)rect {
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColor(context, CGColorGetComponents([self.tintColor CGColor]));
    CGContextFillRect(context, rect);
}
它运行良好,但在iOS 5中不起作用。我需要导航栏的颜色是没有任何梯度固体。我该怎么做


正如我所知,对于iOS 5,替换
drawRect
方法的唯一方法是创建一个子类,但是有没有办法让所有导航控制器使用
UINavigationBar
子类而不是原始类?

在iOS 5中,您可以使用UIAppearance协议设置应用程序中所有UINavigationBar的外观。参考文献:

获得纯色的方法是为导航栏创建自定义图像,并将其设置为UINavigationBars背景。您可能需要创建与UINavigationBar大小相同的图像,至少我是这么做的

在应用程序代理中,执行以下操作:

UIImage *image = [UIImage imageNamed:@"navbarbg.png"];
[[UINavigationBar appearance] setBackgroundImage:image forBarMetrics:UIBarMetricsDefault];
您还必须将
UIAppearanceContainer
协议添加到头文件:

@interface AppDelegate : UIResponder <UIApplicationDelegate, UIAppearanceContainer>

@end
@接口AppDelegate:UIResponder
@结束

通过设置一些颜色或其他东西,而不是图像,您可能可以实现同样的效果。但我发现这是一个简单的解决方案。

这涵盖了iOS 5和iOS 4.3及更早版本


这更像是一种黑客行为,对我来说一直都很有效。 这需要在AppDelegate文件中

//Create  a size struct.
CGSize size = CGSizeMake(768, 50);

//CReate a imagecontext from a non-existing image. You can use a existing image as well, in that case the color will be the color of the image. 
UIImage *backgroundImage = [UIImage imageNamed:@"nonexist.png"];

UIGraphicsBeginImageContext(size);

[backgroundImage drawInRect:CGRectMake(0,0,size.width,size.height)];

UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();

UIGraphicsEndImageContext();

self.navigationController = [[UINavigationController alloc]initWithRootViewController:self.viewController];
将背景色设置为您选择的颜色

[self.navigationController.view setBackgroundColor:[UIColor blackColor]];

self.window.rootViewController = navigationController;
[self.window makeKeyAndVisible];

//Most important line.
[navigationController.navigationBar setBackgroundImage: newImage forBarMetrics:UIBarMetricsDefault];

这应该是纯色的吗?它看起来不管用。你说的“纯色”是什么意思?至少它可以与
tintColor
一起使用。您可以在UIKit框架的头文件中看到
UIAppearance
协议支持的属性和方法。受支持的应用程序在其行的末尾编写了
UI\u外观\u协议
。以
UINavigationBar
为例:它有6个受支持的属性/方法。使用此解决方案时,我得到了2 px的偏移量。它在屏幕顶部显示为一条非常细的黑线。我怎样才能解决这个问题?否则,这是一个很好的答案,因为它不依赖于覆盖导航bar@Hgeg,听起来很奇怪。。您是否使用图像作为背景?检查图像是否与导航栏大小相同。@matsr-Yup。那是我的问题。图像比率与导航栏大小不同。谢谢你的帮助。