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.
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
Funfunfun...
There are two layer properties you can use (in either case you have to iterate over the layers):
CALayer.name
"is used by some layout managers to identify a layer". Set it to something reasonably guaranteed to be unique (e.g. "MyClassName.gradient").CALayer.style
is a dictionary. You can use keys which aren't used by CoreAnimation (e.g. NSMutableDictionary * d = [NSMutableDictionary dictionaryWithDictionary:layer.style]; [d setValue:[NSNumber numberWithBool:YES] forKey:@"MyClassName.gradient"]; layer.style = d;
). This might be useful to associate arbitrary data with a view (such as the index path of the cell containing a text field...).(I'm assuming that [NSDictionary dictionaryWithDictionary:nil]
returns the empty dictionary instead of returning nil or throwing an exception. The corresponding thing is true for [NSArray arrayWithArray:nil]
.)
However, the extra code complexity, performance penalty, and chance of getting it wrong probably outweigh the small decrease in memory usage. 4 bytes per view is not that much if you have a handful of views (and even if you have loads, 4 bytes is the memory used by a single pixel!).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With