'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:[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:[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:[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:[4]

Swift 2.0:

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

or

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

Solution 5:[5]

Swift 5:

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

layer.removeAllAnimations()
layer.removeFromSuperlayer()

Solution 6:[6]

For swift5 to remove CAShapeLayer from added view

guard let sublayers = self.view.layer.sublayers else { return }

for sublayer in sublayers where sublayer.isKind(of: CAShapeLayer.self) {
        sublayer.removeFromSuperlayer()
}

Solution 7:[7]

Swift 4.1

self.view.layer.sublayers?.removeAll()

or if in a UIView sub-class just

layer.sublayers?.removeAll()

Solution 8:[8]

If you want to delete all sublayers and add a new one, you can easily do:

rootLayer.sublayers = [layer1] // adding one layer

rootLayer.sublayers = [layer1, layer2, ...] // adding two or more layers

This could be helpful, if you work with tableview or collectionview cells. You don't need to call prepareForReuse for removing the sublayers.

Solution 9:[9]

Simple one liner in SWIFT 4.

self.view.layer.sublayers.removeAll()

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2
Solution 3 Samuel Liew
Solution 4 Alvin George
Solution 5 Matias Jurfest
Solution 6 Luchi Parejo Alcazar
Solution 7 JonJ
Solution 8 Sean Stayns
Solution 9 Rmalmoe