iphoneuiviewcalayer

Removing a CALayer at index 0


I've added a gradient layer:

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

And later on in another method I want to remove this layer. I figured I should get the array of sublayers then get the sublayer at index 0 and call removeFromSuperlayer on it. Is this the correct way or if not can you do it?

Cheers.


Solution

  • You can do it the way you described but it isn't so reliable. The problem is that if you do anything with the sublayers in between the addition and removal, the index of the sublayer can change and you end up removing something you didn't want to.

    The best thing is to keep a reference to that layer and later when you want to remove it just call [theLayer removeFromSuperlayer]

    Hope it helps