有时,app需要有渐变色效果,如果使用图片,当然也可以,但图片是很吃资源的,并且不能灵活改变颜色。这时可以考虑使用CAGradientLayer这个类来实现。
有两种方案
- 使用继承方式
- 使用
Category
继承和类别的方式都可以,在某些方面类别更好一些
在 .h
文件 声明方法
-(void)setGradientBackgroundColorWithColors:(NSArray *)colors;
在 .m
实现方法
tatic float const kDefaultOpacity = 0.5f;
-(void)setGradientBackgroundColorWithColors:(NSArray *)colors{
NSMutableArray *cgcolors = [NSMutableArray arrayWithCapacity:colors.count];
[colors enumerateObjectsUsingBlock:^(id _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
[cgcolors addObject:(id)[obj CGColor]];
}];
CAGradientLayer *gradientLayer = [CAGradientLayer layer];
gradientLayer.opacity = self.translucent ? kDefaultOpacity : 1.f;
self.barTintColor = [UIColor clearColor];
gradientLayer.frame = CGRectMake(0, -20, kScreenW, CGRectGetMaxY(self.bounds) + 20);
gradientLayer.colors = cgcolors;
[self.layer insertSublayer:gradientLayer atIndex:1];
}
注:这里渐变方向,渐变点都是写死了的,你可以根据实际需求做出调整
//经过一段时间使用发现,这种写法有问题,当你在NavigationController的某一个childViewController设置self.navigationController.navigationBar.hidden = YES;
即某一个VC中需要隐藏导航栏(我这边是rootViewController需要隐藏),在其他子控制器(未隐藏)设置 self.navigationItem
的 title
或titleView
会出现不显示的问题
解决方案:
通过查看图层可以获悉设置背景色的视图类名为 _UIBarBackground
因此,可以不必在navBar中插入子图层 (subLayer) (这也是出现这个bug的原因所在) ,将渐变图层加入到 _UIBarBackground
中,代码如下:
-(void)setGradientBackgroundColorWithColors:(NSArray *)colors{
NSMutableArray *cgcolors = [NSMutableArray arrayWithCapacity:colors.count];
[colors enumerateObjectsUsingBlock:^(id _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
[cgcolors addObject:(id)[obj CGColor]];
}];
CAGradientLayer *gradientLayer = [CAGradientLayer layer];
gradientLayer.opacity = self.translucent ? kDefaultOpacity : 1.f;
self.barTintColor = [UIColor clearColor];
gradientLayer.frame = CGRectMake(0, 0, kScreenW, CGRectGetMaxY(self.bounds) + 20);
gradientLayer.colors = cgcolors;
// [self.layer insertSublayer:gradientLayer atIndex:1];
for (UIView *subv in self.subviews) {
if ([subv isKindOfClass:NSClassFromString(@”_UIBarBackground”)]) {
[subv.layer addSublayer:gradientLayer];
}
}
好了问题解决了O(∩_∩)O~~