修复-线程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()

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

感谢您的耐心

问题是,如果用户在绘制任何内容之前单击按钮清除画布,则会发生错误,因为path只在touchesMoved()中分配了一个值。

您可能想要更改

var path:UIBezierPath!

var path:UIBezierPath?

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

附言:看看这个答案。它提供了许多关于期权使用的信息。

最新更新