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?
I think the error is you delete all sublayers,not the ones you added. keep a property to save the sublayers you added
Then try
Update with Leo Dabus suggest,you can also just set a name of layer.
Then check