remove all subLayers from a view

In an animation I added a lot of sublayers to a view, with:

[self.view.layer addSublayer:layer1];
[self.view.layer addSublayer:layer2];

....

I would like to remove all sublayers with an action. I already tried with this suggestion of a similar question:

rootLayer.sublayers = nil;

but it doesn't work...

Could you help me? Than you!


Solution 1:

The sublayers property of a CALayer object returns a copy of the array. Setting it no nil does nothing about the sublayers. This however will do:

for (CALayer *layer in self.view.layer.sublayers) {
    [layer removeFromSuperlayer];
}

Or, in Swift

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

Solution 2:

Swift 3.0 & Swift 4.0

Set the sublayers property to nil to remove all sublayers from a view.

view.layer.sublayers = nil

also you can add

.removeAll()

Solution 3:

This worked for me and fixed the crash:

[self.view.layer.sublayers makeObjectsPerformSelector:@selector(removeFromSuperlayer)]

I changed the view with my image UImageview, and the crash is gone.

Solution 4:

Swift 2.0:

    for layer: CALayer in self.view.layer.sublayers! {
        layer.removeFromSuperlayer()
    }

or

    self.view.layer.performSelector("removeFromSuperlayer")

Solution 5:

Swift 5:

You can either remove the layer itself or iterate through them and do the following:

layer.removeAllAnimations()
layer.removeFromSuperlayer()