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:58

Calling rootLayer.sublayers = nil; can cause a crash (e.g. if, under iOS 8, you call removeFromSuperview twice on the view owning rootLayer).

The right way should be:

[[rootLayer.sublayers copy] makeObjectsPerformSelector:@selector(removeFromSuperlayer)]

The call to copy is needed so that the array on which removeFromSuperlayer is iteratively called is not modified, otherwise an exception is raised.

查看更多
3楼-- · 2019-01-16 12:59

How about using reverse enumeration?

NSEnumerator *enumerator = [rootLayer.sublayers reverseObjectEnumerator];
for(CALayer *layer in enumerator) {
    [layer removeFromSuperlayer];
}

Because the group in sublayers are changed during enumeration, if the order is normal. I would like to know the above code's result.

查看更多
登录 后发表回答