UINavigationBar,纯色iOS 5

时间:2011-11-25 08:02:56

标签: ios5 uinavigationbar customizing

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

- (void) drawRect:(CGRect)rect {
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColor(context, CGColorGetComponents([self.tintColor CGColor]));
    CGContextFillRect(context, rect);
}

效果很好,但不适用于iOS 5.我需要导航栏颜色为实心,没有任何渐变。我该怎么做?

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

3 个答案:

答案 0 :(得分:13)

在iOS 5中,您可以使用UIAppearance协议设置应用中所有UINavigationBars的外观。参考:link

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

在您的app delegate中,执行以下操作:

UIImage *image = [UIImage imageNamed:@"navbarbg.png"];
[[UINavigationBar appearance] setBackgroundImage:image forBarMetrics:UIBarMetricsDefault];

您还必须将UIAppearanceContainer协议添加到头文件中:

@interface AppDelegate : UIResponder <UIApplicationDelegate, UIAppearanceContainer>

@end

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

答案 1 :(得分:1)

这包括iOS 5和iOS 4.3及更早版本

https://gist.github.com/1774444

答案 2 :(得分:0)

这更像是一个黑客,并一直为我工作。 这需要在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];