3

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

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

它工作得很好,但在 iOS 5 中不行。我需要导航栏颜色是纯色的,没有任何渐变。我该怎么做?

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

4

3 回答 3

13

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

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

在您的应用程序委托中,执行以下操作:

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

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

@interface AppDelegate : UIResponder <UIApplicationDelegate, UIAppearanceContainer>

@end

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

于 2011-11-25T09:10:07.510 回答
1

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

https://gist.github.com/1774444

于 2012-06-19T14:14:44.670 回答
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];
于 2013-04-13T00:29:11.993 回答