首页 > 解决方案 > 修复 - 线程 1:致命错误:在展开可选值时意外发现 nil

问题描述

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

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()

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

感谢您的耐心等待

标签: swiftxcode10forced-unwrapping

解决方案


问题是,如果用户在绘制任何内容之前单击按钮以清除画布,则会发生错误,因为path仅在touchesMoved().

你可能想改变

var path:UIBezierPath!

var path:UIBezierPath?

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

PS看看这个答案。它提供了很多关于使用选项的信息。


推荐阅读