如何制作UIView子类的{C 44}的CAGradientLayer子类支持层

时间:2017-05-25 04:03:18

标签: calayer cagradientlayer

我创建了CAGradientLayer的子类,其中包含colorsstartPointendPoint的所需值。它看起来像这样:

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")
    }

}

我在Playground文件中调用以下初始化程序:

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

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

1 个答案:

答案 0 :(得分:1)

事实证明,当我设置.cgColor的{​​{1}}属性时,我忘记将colors添加到渐变的颜色中。将所需的GradientBackgroundLayer添加到.cgColor个实例解决了我的问题。