Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove CALayers from Parent UIView

Tags:

ios

swift

calayer

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?

like image 526
jwade502 Avatar asked Jun 09 '15 01:06

jwade502


1 Answers

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)
        }
    }
}
like image 165
Leo Avatar answered Oct 07 '22 22:10

Leo