CAGradientLayer send to back

AlexWien picture AlexWien · Jun 22, 2013 · Viewed 9.7k times · Source

I have a UIViewController where I create a background gradient with

    CAGradientLayer *gradient = [CAGradientLayer layer];
    ...
    gradient.frame = frame;
    self.backGradient = gradient;
    [self.view.layer insertSublayer:gradient atIndex:0];

it works fine, later I have to send the subview _selectionFrame of my view controller to back:
(I often need to send the _selectionFrame to back and to front, for animation and drawing purpose)

self is the viewController:

[self.view sendSubviewToBack:_selectionFrame]; 

However this sends the _selectionFrame behind the gradient. I want it just above the gradient but below every other subview. The problem is that the gradient is not a view, so i cannot use the functions for the gradient.
I would like to call [self.view sendSubviewToBack:gradient];

But this does not work.

Answer

Demosthese picture Demosthese · Apr 12, 2018

.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)