渐变色的简单实现

let gradient  = CAGradient ()
gradient .  = self.view.bounds
gradient .colors = [UIColor(hex: \"ffffff\").cgColor, UIColor(hex: \"000000\").cgColor]
view. .addSub (gradient )

写成扩展的自定义方法

import UIKit

extension UIView {
    
    public func addGradient (
        start: CGPoint = CGPoint(x: 0, y: 0), //渐变起点
        end: CGPoint = CGPoint(x: 1, y: 1), //渐变终点
         : CGRect,
        colors: [CGColor]
    ) {
        layoutIfNeeded()
        removeGradient ()
        let gradient  = CAGradient ()
        gradient .startPoint = start
        gradient .endPoint = end
        gradient .  =  
        gradient .colors = colors
         .insertSub (gradient , at: 0)
    }
    
    public func removeGradient () {
        guard let  s = self. .sub s else { return }
        for   in  s {
            if  .isKind(of: CAGradient .self) {
                 .removeFromSuper ()
            }
        }
    }
    
}

使用

view.addGradient ( : view.bounds, colors: [UIColor(hex: \"ffffff\").cgColor, UIColor(hex: \"000000\").cgColor])
收藏 打印