gpt4 book ai didi

ios - 不确定如何为现有代码正确设置我的变量。 fatal error : Unexpectedly found nil while implicitly unwrapping an Optional value

转载 作者:行者123 更新时间:2023-12-01 19:36:03 25 4
gpt4 key购买 nike

我目前正在尝试从 viewcontrollers viewdidload() 中的单独类运行一个函数。以前的开发人员团队编写了代码,我正在努力让它工作,因为我对 swift 也很陌生。

我没有包含所有函数,因为它很长,但只是想知道我是否可以得到一些建议,我收到错误“ fatal error :意外发现 nil 同时隐式展开可选值”对于 shapelayer 值,我知道是因为它们还没有被初始化,但我正在努力弄清楚如何正确设置变量而不弄乱整个代码,只是希望得到一些指导。

我确定我可能需要解释更多,但是有很多代码,我整天都在盯着它,如果我需要再上传,请告诉我。

class TraceViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate {

@IBOutlet weak var canvasView: CanvasView!
static var curLetter = "A"

override func viewDidLoad() {
canvasView.letter = TraceViewController.curLetter
canvasView.clearCanvas()
}
}

类(class):
class CanvasView:UIView { 
var lineColour:UIColor!
var lineWidth:CGFloat!
var path:UIBezierPath!
var touchPoint:CGPoint!
var startingPoint:CGPoint!

var initialPoint:CGPoint!

var stroke1Done = false
var stroke2Done = false
var stroke3Done = false
var stroke4Done = false
var stroke5Done = false
var stroke6Done = false
var stroke7Done = false

//Track current stroke and add all the shape layers into an array
var currentStroke = 1
var strokesArray = [CAShapeLayer]()

func drawShapeLayer() {
let shapeLayer = CAShapeLayer()
shapeLayer.path = path.cgPath //error here
shapeLayer.strokeColor = lineColour.cgColor
shapeLayer.lineWidth = lineWidth
shapeLayer.fillColor = UIColor.clear.cgColor
self.layer.addSublayer(shapeLayer)

//Add the shapes in array so that we can track it
self.strokesArray.append(shapeLayer)

self.setNeedsLayout()
}

func clearCanvas() {
guard path != nil else {return}
path.removeAllPoints()
self.layer.sublayers = nil
self.setNeedsDisplay()
print("Hello")
stroke1Done = false
stroke2Done = false
stroke3Done = false
stroke4Done = false
stroke5Done = false
stroke6Done = false
stroke7Done = false

goNext = false

updateStrokePoints()

updateStrokeDifference()

currentStroke = 1
}
}

最佳答案

该错误似乎是因为您在使用它之前没有设置路径。您需要设置 path在实际调用它之前。

第一的:

var path: UIBezierPath?

然后:
path = UIBezierPath()

最后,使用它:
shapeLayer.path = path?.cgPath

另外,记得使用 ?而不是 !强制展开总是不好的做法。

关于ios - 不确定如何为现有代码正确设置我的变量。 fatal error : Unexpectedly found nil while implicitly unwrapping an Optional value,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60100744/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com