Same-ish solution as @Anton Chikin but a little more robust. Notice the override of layerClass
... this way, you don't have to worry about setting the frame and the frame is automatically updated upon rotation & resize.
class GradientView: UIView {
var colorA : UIColor = UIColor.greenColor() {
didSet { updateGradient() }
}
var colorB : UIColor = UIColor.blueColor() {
didSet { updateGradient() }
}
override class func layerClass() -> AnyClass {
return CAGradientLayer.self
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
updateGradient()
}
func updateGradient() {
if let gLayer = layer as? CAGradientLayer {
gLayer.colors = [colorA.CGColor, colorB.CGColor]
}
}
}
If you're using IB, you can set the properties via "User Defined Runtime Attributes".
If you're not using IB, use the other initializer.