[英]Remove CALayers from Parent UIView
There are several questions like this floating around, but no answer that works. 有几个问题像这样漂浮,但没有答案可行。
I'm adding new CALayers to a UIView like so: 我正在为这样的UIView添加新的CALayers:
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. 这会成功删除图像,但下次触摸屏幕时应用程序崩溃,调用main但调试器中没有打印任何内容。 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? 从父视图中删除CALayers的正确方法是什么?
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. 使用Leo Dabus更新建议,您也可以设置图层名称。
newPic.name = "1234"
Then check 然后检查
func deleteDrawing() {
for layer in self.drawingView.layer.sublayers {
if(layer.name == "1234"){
layerArray.removeObject(layer)
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.