user467225
user467225

Reputation: 229

replace CALayer

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?

Upvotes: 0

Views: 2681

Answers (3)

Anomie
Anomie

Reputation: 94794

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.

Upvotes: 1

akashivskyy
akashivskyy

Reputation: 45180

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];

Upvotes: 3

Sam
Sam

Reputation: 1553

    [[view layer] replaceSublayer:[[[view layer] sublayers] objectAtIndex:0] with:gradient];

Upvotes: 4

Related Questions