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?
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:
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.
Swift (short version):
layer.sublayers?.forEach { $0.removeFromSuperlayer() }
I tried to delete just the first sublayer at index 0 and this worked:
The following should work:
Both setting
self.view.layer.sublayers = nil
and[layer removeFromSuperlayer]
will result in crash ifUIView
contains any subview. Best way to removeCALayer
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
While removing just call this,