fixing - Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value

fixing - Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value

我是编码新手,一直在尝试在屏幕上创建一个可以用手指签名的区域。我做了这个盒子,但我正在努力清除它。我做了一个连接到函数的按钮来清除路径,但我似乎无法弄清楚如何在不崩溃的情况下安全地解包信息。

import UIKit

class canvasView: UIView {

    var lineColour:UIColor!
    var lineWidth:CGFloat!
    var path:UIBezierPath!
    var touchPoint:CGPoint!
    var startingPoint:CGPoint!


    override func layoutSubviews() {
        self.clipsToBounds = true
        self.isMultipleTouchEnabled = false

        lineColour = UIColor.white
        lineWidth = 10
    }

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        let touch = touches.first
        startingPoint = (touch?.location(in: self))!
    }

    override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
        let touch = touches.first
        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 = lineColour.cgColor
        shapeLayer.lineWidth = lineWidth
        shapeLayer.fillColor = UIColor.clear.cgColor
        self.layer.addSublayer(shapeLayer)
        self.setNeedsDisplay()
    }

    func clearCanvas() {
        path.removeAllPoints()
        self.layer.sublayers = nil
        self.setNeedsDisplay()
    }

然后我在

之后的最终函数中出现错误
path.removeAllPoints()

如何最好地打开它以防止它崩溃?

感谢您的耐心等待

问题是如果用户点击按钮清除canvas 之前 he/she绘制任何东西,那么就会发生错误,因为path 仅在 touchesMoved().

中赋值

您可能想要更改

var path:UIBezierPath!

var path:UIBezierPath?

虽然这可能看起来很乏味,因为您必须在尝试访问方法或 path 的 属性 的所有地方添加问号,但它更安全,并且示例中的代码不会崩溃.

P.S。查看 this answer。它提供了很多关于使用选项的信息。