gpt4 book ai didi

swift - 可选类型 "CGContext?"的值未展开

转载 作者:行者123 更新时间:2023-11-28 09:43:13 24 4
gpt4 key购买 nike

我尝试在 View 中画一条线,但由于可选类型错误,我的代码无法编译。我是 swift 和 objective-c 的新手,花了很多时间来搜索答案。问题至今没有解决。那么,任何人都可以提供一些线索来解决这个问题吗?

代码:

import UIKit

class DrawLines: UIView {

// Only override draw() if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func draw(_ rect: CGRect) {
//Drawing code
// context
let context = UIGraphicsGetCurrentContext()
CGContextSetLineWidth(context, 3.0)
CGContextSetStrokeColorWithColor(context, UIColor.purpleColor().cgColor)

//create a path
CGContextMoveToPoint(context,0,0)
CGContextAddLineToPoint(context,250,320)

}
}

错误:

enter image description here

最佳答案

UIGraphicsGetCurrentContext() 返回可选,要在您的示例中使用它,您需要调用 context!。最好的使用方法是将它包装在 if-let 中:

if let context = UIGraphicsGetCurrentContext() {
// Use context here
}

或者更好地使用 guard let:

guard let context = UIGraphicsGetCurrentContext() else { return }
// Use context here

关于swift - 可选类型 "CGContext?"的值未展开,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42226158/

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