iOS - How To Remove Previously Added Sublayers Of a UIView

JLT picture JLT · Jun 2, 2016 · Viewed 28.6k times · Source

I have a custom view which is a subclass of UIView. I added some sublayers to the custom view but now I want remove them.

I tried doing this:

self.layer.sublayers = nil;

But this will remove everything including the initial sublayers of the view.

Is there any way to achieve this? Or do I have to reinitialise a new custom view every time?

Note: App runs in iOS 7 and above.

Thanks!

Answer

luckystars picture luckystars · Jun 2, 2016

Keep a reference to the sublayer added Remove the sublayer from the super layer when not needed.

The code would be like:

Obj C:

[thesublayer removeFromSuperlayer]

Swift:

thesublayer.removeFromSuperlayer()

//thesublayer is the name of the layer you want to remove