美文网首页iOS干货ios_UI程序员
iOS一个方法搞定view渐变色

iOS一个方法搞定view渐变色

作者: 水暮竹妖 | 来源:发表于2017-07-01 19:06 被阅读1957次

    Demo

    AZCategory

    使用效果

    //包含头文件UIView+Gradient.h
    
    [self.label setGradientBackgroundWithColors:@[[UIColor redColor],[UIColor orangeColor]] locations:nil startPoint:CGPointMake(0, 0) endPoint:CGPointMake(1, 0)];
    
    [self.btn setGradientBackgroundWithColors:@[[UIColor redColor],[UIColor orangeColor]] locations:nil startPoint:CGPointMake(0, 0) endPoint:CGPointMake(1, 0)];
    
    [self.tempView setGradientBackgroundWithColors:@[[UIColor redColor],[UIColor orangeColor]] locations:nil startPoint:CGPointMake(0, 0) endPoint:CGPointMake(1, 0)];
    
    

    常规方案

    说起颜色渐变一般来说有两种实现方式,一是使用CAGradientLayer而是使用Core Graphics的相关方法,具体可参考ios实现颜色渐变的几种方法

    问题

    CAGradientLayer可以说是实现起来比较方便的一个方案了,但是对于Autolayout来说,我们需要更新CAGradientLayerframe,这就得增加不少代码,而且代码会散布在其他方法中,这就不是很友好了。

    优化方案

    原理

    我们知道UIView显示的内容实际是绘制在CALayer上的,默认情况下创建一个UIView时会创建一个CALayer作为UIViewroot layer,那么如果我们直接把这个root layer替换成CAGradientLayer就能直接实现渐变效果,而且跟随UIViewframe变化。

    那么如何替换呢?UIView有个+layerClass类方法,官方描述:

    Returns the class used to create the layer for instances of this class.
    This method returns the CALayer class object by default. Subclasses can override this method and return a different layer class as needed. For example, if your view uses tiling to display a large scrollable area, you might want to override this method and return the CATiledLayer class.
    This method is called only once early in the creation of the view in order to create the corresponding layer object.

    大概意思就是系统默认会返回CALayer类,但是如果你重写了这个类方法,那么就会返你return的类,从而创建你需要的layer

    在实际实现这个分类的时候发现+layerClass有点类似+load方法,即只要文件在项目中,就会调用该方法,不需要显式包含头文件。

    实现

    我们创建一个UIView的分类UIView+Gradient,利用runtime添加CAGradientLayer的一些属性以及设置背景色的方法,如下:

    //UIView+Gradient.h
    @property(nullable, copy) NSArray *colors;
    @property(nullable, copy) NSArray<NSNumber *> *locations;
    @property CGPoint startPoint;
    @property CGPoint endPoint;
    
    + (UIView *_Nullable)gradientViewWithColors:(NSArray<UIColor *> *_Nullable)colors locations:(NSArray<NSNumber *> *_Nullable)locations startPoint:(CGPoint)startPoint endPoint:(CGPoint)endPoint;
    
    - (void)setGradientBackgroundWithColors:(NSArray<UIColor *> *_Nullable)colors locations:(NSArray<NSNumber *> *_Nullable)locations startPoint:(CGPoint)startPoint endPoint:(CGPoint)endPoint;
    
    

    然后在.m文件中对重写类方法+layerClass以及实现相关设置:

    
    //UIView+Gradient.m
    
    + (Class)layerClass {
        return [CAGradientLayer class];
    }
    
    + (UIView *)gradientViewWithColors:(NSArray<UIColor *> *)colors locations:(NSArray<NSNumber *> *)locations startPoint:(CGPoint)startPoint endPoint:(CGPoint)endPoint {
        UIView *view = [[self alloc] init];
        [view setGradientBackgroundWithColors:colors locations:locations startPoint:startPoint endPoint:endPoint];
        return view;
    }
    
    - (void)setGradientBackgroundWithColors:(NSArray<UIColor *> *)colors locations:(NSArray<NSNumber *> *)locations startPoint:(CGPoint)startPoint endPoint:(CGPoint)endPoint {
        NSMutableArray *colorsM = [NSMutableArray array];
        for (UIColor *color in colors) {
            [colorsM addObject:(__bridge id)color.CGColor];
        }
        self.colors = [colorsM copy];
        self.locations = locations;
        self.startPoint = startPoint;
        self.endPoint = endPoint;
    }
    
    

    然后就能像最开始提到的那样轻松的一句话设置渐变背景色了。

    注意事项

    • 大部分View在设置colors属性后原有的backgroundColor属性会失效,即不管backgroundColor设置的是什么颜色,都会显示渐变色,要显示正常的backgroundColor只需要将colors设置成nil
    // colors优先级高于backgroundColor的View
        UIView
        UIButton 
        UIImageView
        UITextView
        UITextField
        UISlider
        UIStepper
        UISwitch
        UISegmentedControl
    
    • 在实测中发现UILabel在设置colors后还是会显示backgroundColor,要显示渐变色需要将backgroundColor设置为clearColor

    • 虽然在UIView的分类中重写了+layerClass,但是有可能存在一些View 已经重写了+layerClass,那么就有可能该View的layer并不是CAGradientLayer,而是其他类型的layer,如UILabellayer其实是_UILabelLayer,我们在设置layer属性时不能确保这个layer就是CAGradientLayer,需要加个判断:

       if ([self.layer isKindOfClass:[CAGradientLayer class]]) {
            // do something
        }
    

    否则可能会出现崩溃。

    • 对于UILabel这种貌似已经重写过+layerClass方法的view,我目前是直接在其分类中再次重写+layerClass方法
    //  UIView+Gradient.m
        @implementation UILabel (Gradient)
        + (Class)layerClass {
         return [CAGradientLayer class];
        }
        @end
    

    _UILabelLayer替换为CAGradientLayer除了colorsbackgroundColor的优先级不同其他还有什么影响暂时不清楚。

    相关文章

      网友评论

      • 郑一一一一:非常有启发,但是有一个小疑问,你这样子会把所有 view 的 layer 都替换为 gradientLayer,不知道是否对性能会有影响。个人感觉写成子类应该更好一些
        水暮竹妖:@小屁番茄 目前倒是没有发现性能问题,不写成子类是因为这种方式使用起来是最简单的,继承对代码的入侵太强了。
      • 这个优秀瓜:自定义的颜色无法实现渐变。比如#efecea 到 #aa9993
        水暮竹妖:@是个烂番茄呀 [label setGradientBackgroundWithColors:@[[UIColor hex:@"#efecea"],[UIColor hex:@"#aa9993"]] locations:nil startPoint:CGPointMake(0, 0) endPoint:CGPointMake(1, 0)];
        这里用到了第三方String转Color的库
        这个优秀瓜:@水暮竹妖 我直接在DEMO中修改的色值无法实现渐变,可否看看你的修改方式。
        水暮竹妖:实测这两个色值可以实现渐变...
      • doubleJJ:博主,请问如果设置button的titleLabel渐变色怎么弄呢?
        [self.logoutBtn.titleLabel setGradientBackgroundWithColors:@[[UIColor colorWithHexString:@"#806CFF"],[UIColor colorWithHexString:@"#598BFF"]] locations:nil startPoint:CGPointMake(0, 0) endPoint:CGPointMake(1, 0)];
        我这样写整个label都是有颜色的
        水暮竹妖:这个方法本来就是给View设置背景色的,你这么写就是给按钮的Label设置背景色。如果你只是想让字体的颜色渐变,这个方法是不满足需求的
      • 新地球说着一口陌生腔调:你好 你封装了 UIViewController+PushAndPop.h 这个类别是什么作用
        新地球说着一口陌生腔调:@水暮竹妖 嗯 仔细看了运行效果 知道了
        水暮竹妖:控制push同一种VC的数量 https://www.jianshu.com/p/06eca7ee5aeb
      • Kency書傑:谢谢博主
      • 鬼丶白:你好博主 从上往下渐变怎么设置啊
        水暮竹妖:把endPoint设置成(0,1)就可以了,渐变色的方向其实就是沿着startPoint指向endPoint的方向

      本文标题:iOS一个方法搞定view渐变色

      本文链接:https://www.haomeiwen.com/subject/kfdgcxtx.html