swift - 修复 - 线程 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
,但它更安全,并且示例中的代码不会崩溃。
PS看看这个答案。它提供了很多关于使用选项的信息。
推荐阅读
- java - 如何在 java 中读取 JSON 文件并将其存储在 JSONArray 中
- python - 具有多个 Y 轴范围的 Seaborn FacetGrid 图
- gitlab - 在 GitLab CI 中使用 Blackbox 解密文件
- python - 如何正确地将一个 .proto 文件导入另一个文件?
- node.js - 如何将 Firebase 云功能设置为路由到 Firestore 而不是实时数据库
- python - 尝试使用 PIL 和 BytesIO 显示图像但不返回任何内容
- sql - SQL CASE THEN 语句,其中 ID 具有多个值
- node.js - 运行“npm install”:Node-gyp 错误 - MSBUILD.exe 失败,退出代码:1
- mongodb - MongoDB Schema Evolution 最佳实践
- python - 如何匹配使用正则表达式来匹配具有特定开始和结束模式的多行文本