Remove CALayers from Parent UIView

7.5k views Asked by At

There are several questions like this floating around, but no answer that works.

I'm adding new CALayers to a UIView like so:

    func placeNewPicture() {
        let newPic = CALayer()
        newPic.contents = self.pictureDragging.contents
        newPic.frame = CGRect(x: pictureScreenFrame.origin.x - pictureScreenFrame.width/2, y: pictureScreenFrame.origin.y - pictureScreenFrame.height/2, width: pictureScreenFrame.width, height: pictureScreenFrame.height)
        self.drawingView.layer.addSublayer(newPic)
    }

and trying to remove them with:

    func deleteDrawing() {

        for layer in self.drawingView.layer.sublayers {
            layer.removeFromSuperlayer()
        }
    }

This successfully removes the images, but the app crashes the next time the screen is touched, with a call to main but nothing printed in the debugger. There are several situations like this out there, where apps will crash a short time after removing sublayers.

What is the correct way to remove CALayers from their parent View?

1

There are 1 answers

5
Leo On BEST ANSWER

I think the error is you delete all sublayers,not the ones you added. keep a property to save the sublayers you added

    var layerArray = NSMutableArray()

Then try

func placeNewPicture() {
    let newPic = CALayer()
    newPic.contents = self.pictureDragging.contents
    newPic.frame = CGRect(x: pictureScreenFrame.origin.x - pictureScreenFrame.width/2, y: pictureScreenFrame.origin.y - pictureScreenFrame.height/2, width: pictureScreenFrame.width, height: pictureScreenFrame.height)
    layerArray.addObject(newPic)
    self.drawingView.layer.addSublayer(newPic)
}
func deleteDrawing() {

    for layer in self.drawingView.layer.sublayers {
        if(layerArray.containsObject(layer)){
            layer.removeFromSuperlayer()
            layerArray.removeObject(layer)
        }
    }
}

Update with Leo Dabus suggest,you can also just set a name of layer.

newPic.name = "1234"

Then check

func deleteDrawing() {

    for layer in self.drawingView.layer.sublayers {
        if(layer.name == "1234"){
            layerArray.removeObject(layer)
        }
    }
}