It looks like you are using the layer directly and adding it to the view's backing layer. I recommend a simple UIView subclass that encapsulates the gradient behavior. The implementation is quite simple and the the largest benefit is the control you get over where it is rendered in the z dimension. Then you can just use the gradient view as a parent view for your content or if that isn't reasonable in your specific scenario, you could just insert the gradient view as a subview at index 0 using the UIView.insert(_:,at:)
method of UIView instances. This would make your gradient view appear below the other views you add later.
I recently began using gradients in one of my apps. Here is the code I used to define my custom gradient type.
import UIKit
public class AxialGradientView: UIView {
public var colors: [UIColor] = [] {
didSet {
gradientLayer.colors = colors.map { $0.cgColor }
}
}
/// Expressed in a unit coordinate system.
public var startPoint: CGPoint = CGPoint(x: 0.5, y: 0) {
didSet {
gradientLayer.startPoint = startPoint
}
}
/// Expressed in a unit coordinate system.
public var endPoint: CGPoint = CGPoint(x: 0.5, y: 1) {
didSet {
gradientLayer.endPoint = endPoint
}
}
override public class var layerClass: Swift.AnyClass {
get {
return CAGradientLayer.self
}
}
private var gradientLayer: CAGradientLayer {
return layer as! CAGradientLayer
}
}