【问题标题】:UINavigationBar with solid color iOS 5UINavigationBar 与纯色 iOS 5
【发布时间】:2012-01-06 03:52:16
【问题描述】:

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

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

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

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

【问题讨论】:

    标签: ios5 uinavigationbar customizing


    【解决方案1】:

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

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

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

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

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

    @interface AppDelegate : UIResponder <UIApplicationDelegate, UIAppearanceContainer>
    
    @end
    

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

    【讨论】:

    • 这应该适用于纯色吗?看起来好像不行。
    • “纯色”是什么意思?至少它适用于tintColor。您可以在 UIKit 框架的头文件中看到UIAppearance 协议支持的属性和方法。受支持的在行尾写有UI_APPEARANCE_PROTOCOL。以UINavigationBar 为例:它有6 个支持的属性/方法。
    • 当我使用这个解决方案时,我得到了一个 2 px 的偏移量。它在屏幕顶部显示为一条非常细的黑线。我该如何解决?否则这是一个很好的答案,因为它不依赖于覆盖导航栏
    • @Hgeg,这听起来很奇怪..您是否使用图像作为背景?检查图像是否与导航栏大小相同。
    • @matsr 是的。那是我的问题。图像比例与导航栏大小不同。感谢您的帮助。
    【解决方案2】:

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

    https://gist.github.com/1774444

    【讨论】:

      【解决方案3】:

      这更像是一种 hack,并且一直对我有用。 这需要在 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];
      

      【讨论】:

        猜你喜欢
        • 2014-07-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多