Reputation: 6049
I have created a subclass of CAGradientLayer
with desired values for colors
, startPoint
, and endPoint
. It looks like this:
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()
}
}
I also have a subclass of UIView
that I want to have an instance of GradientBackgroundLayer
as its backing layer
. It looks like this:
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")
}
}
I call call the following initializer in a Playground file:
let view = GradientView(frame: CGRect(x: 0, y: 0, width: 400, height: 100))
I get a black view. I see it update if I change the layer
's backgroundColor
, but I can't figure out what I am doing incorrectly to cause the layer to not display the gradient.
Upvotes: 1
Views: 217
Reputation: 6049
It turns out that I forgot to add .cgColor
to the gradient's colors when I set the colors
property of GradientBackgroundLayer
. Adding the required .cgColor
to the UIColor
instances solved my issue.
Upvotes: 1