Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 283
Rudiger Avatar asked Nov 22 '10 22:11

Rudiger


2 Answers

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

like image 173
Jernej Strasner Avatar answered Sep 19 '22 15:09

Jernej Strasner


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!).

like image 38
tc. Avatar answered Sep 18 '22 15:09

tc.