核心动画,self.presentationLayer() 为 nil

Core animation, self.presentationLayer() is nil

我有一个 swift 自定义 CALayer,它有一些动态(实际上 @NSManaged 属性)我已经正确设置了所有内容并且正在调用图层 actionForKey。

override public func actionForKey(key: String!) -> CAAction! {
    switch key {
    case "maxCircles", "numCircles":
        let animation = CABasicAnimation(keyPath: key)
        animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear);
        animation.fromValue = self.presentationLayer().valueForKey(key);
        animation.duration = 0.2
        return animation;
    default:
        return super.actionForKey(key)
    }
}

有时 self.presentationLayer(). 会抛出异常,因为它被隐式解包并且为 nil。在 objective-C 中,代码通常只做:

[[self presentationLayer] valueForKey:key]

它不会崩溃,但我从来没有真正意识到它可以调用 nil 并生成 0 - 这对我来说感觉很不对。不能保证我从零开始制作动画。

在 Swift 中访问 presentationLayer 的正确方法是什么?我应该测试零吗?即:

override public func actionForKey(key: String!) -> CAAction! {
    if ( key == "maxCircles" || key == "numCircles" ) && self.presentationLayer() != nil {

        let animation = CABasicAnimation(keyPath: key)
        animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear);
        animation.fromValue = self.presentationLayer().valueForKey(key);
        animation.duration = 0.2
        return animation;
    }
    return super.actionForKey(key)
}

presentationLayer 属性 returns 是可选的,所以是的,你应该测试 nil。在 Objective-C 中,消息传递 nil 是空操作,因此不会导致您的应用程序崩溃。请记住,安全是 swift 的主要目标之一,因此您需要在此处自行检查。如果你这样写你的函数,它将与 Objective-C 对应的函数类似:

override public func actionForKey(key: String!) -> CAAction! {
    if key == "maxCircles" || key == "numCircles" {
        // Check your presentation layer first before doing anything else
        if let presoLayer = self.presentationLayer() as? CALayer {
            let animation = CABasicAnimation(keyPath: key)
            animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear);
            animation.fromValue = presoLayer.valueForKey(key);
            animation.duration = 0.2
            return animation;
        }
    }
    return super.actionForKey(key)
}

我假设你的其余代码就在这里,只是回答关于 presentationLayer 的可选性的部分。我把你的 switch 换成 if 因为它对我来说更易读。

Matt Long 的解决方案有效。但是,如果您想保留 switch 语法,您可以使用 case … where 语法测试 nil

override func actionForKey(key: String!) -> CAAction! {
    switch key {
    case "maxCircles", "numCircles" where self.presentationLayer() != nil:
        let animation = CABasicAnimation(keyPath: key)
        animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear);
        animation.fromValue = self.presentationLayer().valueForKey(key);
        animation.duration = 0.2
        return animation;
    default:
        return super.actionForKey(key)
    }
}

或者,如果没有表示层,您可以只提供默认值 fromValue

animation.fromValue = self.presentationLayer() != nil ? self.presentationLayer().valueForKey(key) : 0;