0

I am following this answer to create a gradient using a CALayer. The key command is

[view.layer insertSublayer:gradient atIndex:0];

My problem is that I would like to update the gradient regularly. If I call the above code repeatedly, then nothing happens as new gradients are placed under the old ones. See this answer.

My question is: how does one replace a sublayer with another one. I should probably call replaceSublayer:with:. But to do this, I need a reference to the old gradient. Is there a dynamic way of obtaining this. Something like [view.layer getSublayerAtIndex: 0]? Is the easiest way to just store a reference to the current gradient in the viewcontroller?

Ideas?

Community
  • 1
  • 1
user467225
  • 229
  • 1
  • 5
  • 14

3 Answers3

4
    [[view layer] replaceSublayer:[[[view layer] sublayers] objectAtIndex:0] with:gradient];
Sam
  • 1,504
  • 2
  • 13
  • 19
3

If you want to get a sublayer, you should use this method:

[view.layer.sublayers objectAtIndex:0];

Then you can replace the sublayer via

[view.layer replaceSublayer:[view.layer.sublayers objectAtIndex:0] with:yourNewGradient];
akashivskyy
  • 44,342
  • 16
  • 106
  • 116
1

Besides replacing the layer, you can just update the existing CAGradientLayer's colors, locations, and other properties to change the parameters of the displayed gradient.

Anomie
  • 92,546
  • 13
  • 126
  • 145