Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 307
Beppino66 Avatar asked May 28 '12 19:05

Beppino66


2 Answers

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() }
like image 184
Svein Halvor Halvorsen Avatar answered Oct 17 '22 17:10

Svein Halvor Halvorsen


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()
like image 35
Harshil Kotecha Avatar answered Oct 17 '22 17:10

Harshil Kotecha