iOS - How To Remove Previously Added Sublayers Of a UIView

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

Another way to remove specific layer from super layer is to assign unique string in layer.name property. Which you can compare later to identify and remove it out.

for layer in sublayers {
     if layer.name == "masklayer" {
          layer.removeFromSuperlayer()
     }
 }

I did it in Swift 3 using popLast().

self.layer.sublayers?.popLast()

keeping reference is not cool, in some cases you can use

resultImageView.layer.sublayers?.filter{ $0 is CAShapeLayer }.forEach{ $0.removeFromSuperlayer() }

or to be more generic by using CALayer, which removes everything