CAGradientLayer send to back
The simplest solution is not to insert the gradient layer as a sublayer of self.view.layer
. Instead, it should be self.view.layer
. A UIView subclass has a class method layerClass
that lets you say what class its layer should be.
For example, in your UIView
subclass you would add this:
override class var layerClass: AnyClass {
return CAGradientLayer.self
}
And when referencing self.layer
within the view, wrap it a guard let or if let to convert the type like such:
guard let layer = self.layer as? CAGradientLayer else { ... }
Or, it could be the layer of some other subview of self.view
, again easily arranged by using the same class method layerClass
.
Otherwise, you will have to use layer commands, not view commands, to order the sublayers of self.view
. That includes its subviews. In other words, if v
is a subview of self.view
, then v.layer
is a sublayer of self.view.layer
and you can order it among its sublayers by rearranging the sublayers array.
.layer has a sublayers property which is a simple array. So you can insert at any index you want. If you want your new layer to be at the back, just insert it at 0, like this:
let newLayer = CALayer() // your layer that you want at the back
view.layer.insertSublayer(newLayer, at: 0)
Create a view that contains only the gradient