从 UIView 层中删除子层会导致应用崩溃

问题描述

我有一个使用 UITouch 事件绘制 UIBezierPath 的简单视图。在我尝试清除视图之前,一切正常。具体来说,它工作了两次,第三次尝试画一条线时,应用程序崩溃了。

为了增加一点复杂性,UIViewController 被包裹在 UIViewControllerRepresentable 中以用于 SwiftUI 项目,尽管我的直觉是这不是问题的原因。

>

这是代码,我已经隔离了导致崩溃的一行,我只是不知道它为什么会导致崩溃。

import UIKit

class Canvas: UIView {
    
    var lineColor: UIColor!
    var linewidth: CGFloat!
    
    var path: UIBezierPath!
    var touchPoint: CGPoint!
    var startingPoint: CGPoint!
    
    override func layoutSubviews() {
        self.clipsToBounds = true;
        self.isMultipletouchEnabled = false;
        
        lineColor = .white
        linewidth = 10
        
    }
    
    override func touchesBegan(_ touches: Set<UITouch>,with event: UIEvent?) {
        guard let touch = touches.first else { return }
        startingPoint = touch.location(in: self)
        if(path != nil && path.isEmpty == false) {
            clearCanvas()
        }
    }
    
    override func touchesMoved(_ touches: Set<UITouch>,with event: UIEvent?) {
        guard let touch = touches.first else { return }
        touchPoint = touch.location(in: self)
        path = UIBezierPath()
        path.move(to: startingPoint)
        path.addLine(to: touchPoint)
        startingPoint = touchPoint
        drawShapeLayer()
    }
    
    func drawShapeLayer() {
        let shapeLayer = CAShapeLayer()
        shapeLayer.path = path.cgPath
        shapeLayer.strokeColor = lineColor.cgColor
        shapeLayer.linewidth = linewidth
        shapeLayer.fillColor = UIColor.clear.cgColor
        self.layer.addSublayer(shapeLayer)
        self.setNeedsdisplay()
    }
    
    func clearCanvas() {
        path?.removeAllPoints()
        // The next line causes the crash
        self.layer.sublayers?.forEach{ $0.removeFromSuperlayer() }
    }
}

我永远是一个 Swift 菜鸟。来自 Javascript,我对引用和指针以及什么不是很了解。我怀疑与图层相关的东西正在消失,然后应用程序试图访问它,但我无法确定发生这种情况的位置或原因。我假设视图 layerlayer.subLayers 属性将始终存在。

一如既往,非常感谢任何帮助。

编辑:

在诊断中启用 Zombies 后,出现此错误

DowntownControls[7663:5124409] *** -[CALayer convertPoint:fromLayer:]: message sent to deallocated instance 0x1070790f0

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)