Removing all CALayer's sublayers

2019-01-16 12:16发布

I have trouble with deleting all of layer's sublayers. I currently do this manually, but that brings unnecessary clutter. I found many topics about this in google, but no answer.

I tried to do something like this:

for(CALayer *layer in rootLayer.sublayers)
{
    [layer removeFromSublayer];
}

but it didn't work.

Also, i tried to clone rootLayer.sublayers into separate NSArray, but result was the same.

Any ideas?

Edit:

I thought it works now, but I was wrong. It works good with CALayers, but it doesn't work with CATextLayers. Any ideas?

14条回答
迷人小祖宗
2楼-- · 2019-01-16 12:34

Indiscriminately removing all sublayers causes nasty crashes in iOS 7, which can occur much later in the program's execution. I have tested this thoroughly using both rootLayer.sublayers = nil and [rootLayer.sublayers makeObjectsPerformSelector:@selector(removeFromSuperlayer)]. There must be a system-created layer that's getting messed up.

You have to keep your own array of layers and remove them yourself:

[myArrayOfLayersIAddedMyself makeObjectsPerformSelector:@selector(removeFromSuperlayer)];
查看更多
Lonely孤独者°
3楼-- · 2019-01-16 12:36

For sure you can do:
self.layer.sublayers=nil;
as suggested by Pascal Bourque. But it's better to call the setter for sublayers property:
[self.layer setSublayers:nil];
To avoid any clean up issues if there might be.

查看更多
够拽才男人
4楼-- · 2019-01-16 12:41

Swift (short version):

layer.sublayers?.forEach { $0.removeFromSuperlayer() }

查看更多
冷血范
5楼-- · 2019-01-16 12:41

I tried to delete just the first sublayer at index 0 and this worked:

- (UITableViewCell *)tableView:(UITableView *)tableView
         cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    if ([cell.contentView.layer.sublayers count] != 0) {
        [[cell.contentView.layer.sublayers objectAtIndex:0] removeFromSuperlayer];
    }
查看更多
我只想做你的唯一
6楼-- · 2019-01-16 12:43

The following should work:

for (CALayer *layer in [[rootLayer.sublayers copy] autorelease]) {
    [layer removeFromSuperlayer];
}
查看更多
我命由我不由天
7楼-- · 2019-01-16 12:43

Both setting self.view.layer.sublayers = nil and [layer removeFromSuperlayer] will result in crash if UIView contains any subview. Best way to remove CALayer from superLayer is by maintaining an array of layers. For instance that array is arrayOfLayers,

Everytime you add a layer on UIView.sublayer add that layer in this array...

For example

[arrayOfLayers addObject:layer];
[self.view.layer addSublayer:layer];

While removing just call this,

[arrayOfLayers makeObjectsPerformSelector:@selector(removeFromSuperlayer)];
查看更多
登录 后发表回答