如何制作UIView子类的CAGradientLayer子类背衬层
问题描述:
我已创建CAGradientLayer
的子类,其中colors
,startPoint
和endPoint
的期望值。它看起来像这样:如何制作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))
我得到一个黑色的视图。我看到它更新,如果我更改layer
的backgroundColor
,但我无法弄清楚我做错了什么导致图层不显示渐变。
答
事实证明,当我设置GradientBackgroundLayer
的colors
属性时,我忘记了将.cgColor
添加到渐变的颜色。将所需的.cgColor
添加到UIColor
实例解决了我的问题。