如何制作UIView子类的CAGradientLayer子类背衬层

问题描述:

我已创建CAGradientLayer的子类,其中colorsstartPointendPoint的期望值。它看起来像这样:如何制作UIView子类的CAGradientLayer子类背衬层

public final class GradientBackgroundLayer: CAGradientLayer { 

    // MARK: - Properties 

    private let leftColor = UIColor(red: 0.96, 
            green: 0.64, 
            blue: 0.42, 
            alpha: 1.00) 

    private let rightColor = UIColor(red: 0.88, 
            green: 0.36, 
            blue: 0.38, 
            alpha: 1.00) 

    // MARK: - Initialization 

    public override init() { 
     super.init() 
     configure() 
    } 

    public override init(layer: Any) { 
     super.init(layer: layer) 
     configure() 
    } 

    required public init?(coder aDecoder: NSCoder) { 
     fatalError("init(coder:) has not been implemented") 
    } 

    // MARK: - Helpers 

    private func configureColors() { 
     colors = [leftColor, 
        rightColor] 
    } 

    private func configureLocations() { 
     gradientLayer.locations = [0.1, 
            0.9] 
     } 

    private func configure() { 
     configureColors() 
     configureLocations() 
    } 

} 

我也有UIView,我希望有GradientBackgroundLayer一个实例作为其后盾layer一个子类。它看起来像这样:

public final class GradientView: UIView { 

    // MARK: - Properties 

    override public class var layerClass: AnyClass { 
     return GradientBackgroundLayer.self 
    } 

    // MARK: - Initialization 

    public override init(frame: CGRect) { 
     super.init(frame: frame) 
    } 

    public required init?(coder aDecoder: NSCoder) { 
     fatalError("init(coder:) has not been implemented") 
    } 

} 

我打电话请拨打以下初始化在操场文件:

let view = GradientView(frame: CGRect(x: 0, y: 0, width: 400, height: 100)) 

我得到一个黑色的视图。我看到它更新,如果我更改layerbackgroundColor,但我无法弄清楚我做错了什么导致图层不显示渐变。

事实证明,当我设置GradientBackgroundLayercolors属性时,我忘记了将.cgColor添加到渐变的颜色。将所需的.cgColor添加到UIColor实例解决了我的问题。