带渐变的UINavigationBar tintColor

pbe*_*ery 10 iphone cocoa-touch interface-builder

我想改变tintColorUINavigationBar的programmaticaly 并保持渐变,就像在Interface Builder中一样.

当我更改tintColor我的代码时,渐变消失,但当我更改tintColor接口生成器时,保持渐变.

有任何想法吗?

Rya*_*ews 20

所以这是一个古老的问题,但当我在寻找听起来像这个问题的东西时,我偶然发现了它,但却有所不同.希望它会帮助别人(或其他人会告诉我更好的方式)......

如何在UINavigationBar上实现自定义渐变?

首先,让我们按照通常的方式获得自定义渐变(作为CALayer):

- (CALayer *)gradientBGLayerForBounds:(CGRect)bounds
{
    CAGradientLayer * gradientBG = [CAGradientLayer layer];
    gradientBG.frame = bounds;
    gradientBG.colors = @[ (id)[[UIColor redColor] CGColor], (id)[[UIColor purpleColor] CGColor] ];
    return gradientBG;
}
Run Code Online (Sandbox Code Playgroud)

我们去了,一个看起来像朋克摇滚歌手的可疑化妆选择的渐变,这很好,因为这个代码适用于假设的应用程序我有一个朋克摇滚我口袋里有可疑的口味.那个名字我有点太长了..

现在我想在我的UINavigationBar上使用这一层,这应该很容易吗?只需将其添加为子图层,对吧?这里的问题是它将掩盖UINavigationController为您提供的精彩按钮和内容.那很糟.

相反,让我们看看我们在iOS5 +中使用的非常方便的方法来改变我们应用中所有UINavigationBar的外观:

[[UINavigationBar appearance] setBackgroundImage:SOME_IMAGE
                                   forBarMetrics:UIBarMetricsDefault];
Run Code Online (Sandbox Code Playgroud)

这里唯一的问题是我们没有UIImage,我们有一个CALayer.什么是朋克摇滚乐爱好者?

CALayer * bgGradientLayer = [self gradientBGLayerForBounds:ONE_OF_YOUR_NAV_CONTROLLERS.navigationBar.bounds];
UIGraphicsBeginImageContext(bgGradientLayer.bounds.size);
[bgGradientLayer renderInContext:UIGraphicsGetCurrentContext()];
UIImage * bgAsImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
Run Code Online (Sandbox Code Playgroud)

所以现在我们已经将我们的CALayer转换为UIImage(希望如此),所以剩下的就是设置它:

if (bgAsImage != nil)
{
    [[UINavigationBar appearance] setBackgroundImage:bgAsImage
                                       forBarMetrics:UIBarMetricsDefault];
}
else
{
    NSLog(@"Failded to create gradient bg image, user will see standard tint color gradient.");
}
Run Code Online (Sandbox Code Playgroud)

我喜欢这个解决方案是

  • 我的应用程序中所有UINavigationBar的集中代码(在AppDelegate中)
  • tintColor仍然适用于所有UINavigation按钮(返回,编辑等)
  • 如果UIImage创建失败,我的UINavigationBar仍将遵循tintColor
  • 我不必依赖实际的图像资源/易于更新

但我仍然不相信这是最好的方式.所以,如果它对您有所帮助,请告诉我如何改进它.

〜谢谢


car*_*los 14

将barStyle设置为UIBarStyleBlackTranslucent将tintColor设置为:

navigationBar.tintColor = [UIColor colorWithRed:.7 green:.5 blue:.2 alpha:1];
Run Code Online (Sandbox Code Playgroud)

这将设置适当的渐变.使用您需要的任何组合.

  • UIBarStyleBlackTranslucent已被弃用.最好使用navigationBar.barStyle = UIBarStyleBlack; navigationBar.translucent = YES; (7认同)