先来看效果图:
UIView的颜色渐变参考:http://www.jianshu.com/p/05889da18b2d
在使用上述方式设置导航条颜色渐变的时候,会发现导航条的颜色是渐变了,但是标题、左右按钮全部看不见了。
self.navigationController.navigationBar.layer .addSublayer(gradientLayer)
这是因为在navigationBar上加了一层layer之后,把原来的标题、左右按钮全部覆盖掉了,所以导致看不见。
那么如何来解决导航条颜色渐变的问题呢?
锵锵锵~答案如下:
- (CALayer *)gradientBGLayerForBounds:(CGRect)bounds
{
CAGradientLayer *gradientLayer = [CAGradientLayer layer];
gradientLayer.colors = @[(__bridge id)[UIColor redColor].CGColor, (__bridge id)[UIColor yellowColor].CGColor];
gradientLayer.locations = @[@0, @1.0];
gradientLayer.startPoint = CGPointMake(0, 0);
gradientLayer.endPoint = CGPointMake(1.0, 0);
gradientLayer.frame = bounds;
return gradientLayer;
}
//设置导航条的背景为渐变色
- (void)updateNavigationBarBGColor
{
CALayer * bgLayer = [self gradientBGLayerForBounds:CGRectMake(0, 0, self.navigationController.navigationBar.frame.size.width, self.navigationController.navigationBar.frame.size.height)];
UIGraphicsBeginImageContext(bgLayer.bounds.size);
[bgLayer renderInContext:UIGraphicsGetCurrentContext()];
UIImage * bgAsImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
if (bgAsImage != nil)
{
[self.navigationController.navigationBar setBackgroundImage:bgAsImage forBarMetrics:UIBarMetricsDefault];
}
else
{
NSLog(@"Failded to create gradient bg image, user will see standard tint color gradient.");
}
}
其中CAGradientLayer中相关属性说明参考:http://www.jianshu.com/p/05889da18b2d
网友评论