I am following this answer to create a gradient using a CALayer
. The
key comman开发者_StackOverflow中文版d 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?
[[view layer] replaceSublayer:[[[view layer] sublayers] objectAtIndex:0] with:gradient];
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];
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.
精彩评论