Swift drawInRect无法解包Optional.None

时间:2014-07-03 20:10:24

标签: ios swift xcode6

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

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

fatal error: Can't unwrap 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行,我可以暂时获得绘图,如果经过touchMoved ...但是由于上下文被重置,它不会在图像上持续

1 个答案:

答案 0 :(得分:2)

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

要打开图片并在图片可用时使用drawInRect,请使用

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