【发布时间】:2017-05-25 04:03:17
【问题描述】:
我创建了 CAGradientLayer 的子类,并为 colors、startPoint 和 endPoint 设置了所需的值。它看起来像这样:
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,我会看到它会更新,但我无法弄清楚我做错了什么导致图层不显示渐变。
【问题讨论】: