ios - Swift drawInRect 无法展开 Optional.None

标签 ios swift xcode6

我正在尝试将我的旧代码从 objective-c 转换为 swift。

但是我在 self.image.drawInRect() 上得到以下错误:

fatal error :无法解包 Optional.None

我有一个名为 Canvas 的类,它是 UIImageView 的子类,它在 Storyboard上设置,并在我唯一的 ViewController 上初始化:

init(coder aDecoder: NSCoder!) {
    pref = NSUserDefaults.standardUserDefaults()

    currentPlay = Play()
    canvas = Canvas(coder: aDecoder)
    super.init(coder: aDecoder)
}

这是我的 Canvas.Swift

import UIKit

class Canvas: UIImageView {

    var path:UIBezierPath = UIBezierPath()
    var drawColor:UIColor = UIColor.greenColor()
    var lastLocation:CGPoint = CGPoint()

    init(coder aDecoder: NSCoder!) {
        super.init(coder: aDecoder)
    }

    // handling touches

    override func touchesBegan(touches: NSSet!, withEvent event: UIEvent!) {
        let touch:UITouch  = touches.anyObject() as UITouch
        lastLocation = touch.locationInView(self.superview)
    }

    override func touchesMoved(touches: NSSet!, withEvent event: UIEvent!) {
        let touch:UITouch  = touches.anyObject() as UITouch
        let location = touch.locationInView(self.superview)

        UIGraphicsBeginImageContext(self.frame.size)
        self.image.drawInRect(self.frame)
        path = UIBezierPath()
        path.lineWidth = 8;
        path.lineCapStyle = kCGLineCapRound;
        drawColor.setStroke()

        path.moveToPoint(CGPointMake(lastLocation.x, lastLocation.y))

        path.addLineToPoint(CGPointMake(location.x, location.y))
        path.stroke()

        self.image = UIGraphicsGetImageFromCurrentImageContext();
        lastLocation = location

        path.closePath()
        UIGraphicsEndImageContext();
    }

    override func touchesEnded(touches: NSSet!, withEvent event: UIEvent!) {
        // nothing yet
    }
}

ps:如果我删除 drawInRect 线,如果通过 touchedMoved,我可以暂时获得绘图...但是由于上下文被重置,它不会保留在图像上

最佳答案

UIImageView 通常是用图像初始化的 - 但在您的情况下,您正在取消存档并假设 image 属性包含有效图像。由于 image 属性是隐式展开的(它被定义为 var image: UIImage!),它不会给你一个编译时错误,而是在运行时崩溃。

要打开图像并在图像可用时使用 drawInRectself.image.drawInRect(self.frame) 替换为

if let image = self.image {
    image.drawInRect(self.frame)
}

关于ios - Swift drawInRect 无法展开 Optional.None,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24562527/

相关文章:

objective-c - @try/@catch 不捕获异常

ios - NSURLErrorDomain 代码=-997 "Lost connection to background transfer service"

ios - 我们可以在 Testflight 上分发使用企业开发人员程序签名的 ipa 文件吗?

ios - AppDelegate:此类与键的键值编码不兼容---

swift - 使用自定义对象实现计数排序

cocoa - 为什么数据不会显示在我的 NSTableView(基于 View )中?

ios - 不允许代理角色编辑用户

ios - 保护对 NSManaged 对象数组的读/写访问

ios - Swift 如何更改 View (而非所有 View )的状态栏 lise 导航栏的背景颜色

ios - 操作系统 :Making CocoaPods compatible with older version install