【问题标题】:value of optional type "CGContext?" not unwrapped可选类型“CGContext?”的值未打开
【发布时间】:2017-02-14 12:26:27
【问题描述】:

我尝试在视图中画一条线,但由于可选类型错误,我的代码无法编译。我是 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)

    }
}

错误:

【问题讨论】:

  • 只需点击Fix-it选项即可。
  • @NiravD 感谢您的回答。它可能会通过您的建议解决问题,但它不能解决我的问题。你能告诉我导致这个问题的原因吗?
  • 你的意思是它不能解决我的问题,修复后它会消除你当前遇到的错误。
  • @NiravD 错误消失了,但我的代码已更改。 CGContextSetLineWidth 更改为 context.setLineWidth。似乎从未使用过 CGContextSet。
  • 检查@vadian 的答案。

标签: swift swift3 cgcontext


【解决方案1】:

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

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

甚至更好地使用guard let:

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

【讨论】:

  • 使用UIView时保证上下文存在
【解决方案2】:

在这种情况下,解决方案是在获取上下文时使用!

let context = UIGraphicsGetCurrentContext()!

当没有当前上下文时,应用程序将崩溃,这意味着您做错了什么。

【讨论】:

    【解决方案3】:

    只是强制解包上下文,它是 100% 安全的,但只能解决一个问题。

    来自UIGraphicsGetCurrentContext的文档:

    当前图形上下文默认为nil在调用其drawRect: 方法之前,视图对象将一个有效的上下文推送到堆栈上,使其成为当前的

    在 Swift 3 中(假设来自 draw 签名)图形语法发生了显着变化:

    class DrawLines: UIView {
    
        override func draw(_ rect: CGRect) {
            let context = UIGraphicsGetCurrentContext()!
            context.setLineWidth(3.0)
            context.setStrokeColor(UIColor.purple.cgColor)
    
            //create a path
    
            // context.beginPath()
            context.move(to: CGPoint())
            context.addLine(to: CGPoint(x:250, y:320))
            // context.strokePath()
    
        }
    }
    

    PS:但要画线,您应该取消注释 beginPath()strokePath() 线。

    【讨论】:

    • 我删除!从 UIGraphicsGetCurrentContext 的末尾而不是添加?在上下文结束时,程序可以编译并运行。如果我尝试这种方式有什么不同吗?
    • 尾随感叹号并不总是坏的或不安全的。根据文档,添加感叹号绝对安全。问号使它/保持它是可选的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多