【发布时间】:2021-03-30 06:06:19
【问题描述】:
我试图了解这种方法 run(forKey:object:arguments:) 是如何在 Apple 的 documentation 的以下代码中完全运行的:
let delegate = LayerDelegate()
lazy var sublayer: CALayer = {
let layer = CALayer()
layer.delegate = self.delegate
return layer
}()
func moveSublayer() {
guard let action = sublayer.action(forKey: "moveRight") else {
return
}
action.run(forKey: "transform", object: sublayer, arguments: nil) // this line
}
class LayerDelegate: NSObject, CALayerDelegate {
func action(for layer: CALayer, forKey event: String) -> CAAction? {
guard event == "moveRight" else {
return nil
}
let animation = CABasicAnimation()
animation.valueFunction = CAValueFunction(name: CAValueFunctionName.translateX)
animation.fromValue = 1
animation.toValue = 300
animation.duration = 2
return animation
}
}
我对来自action.run(forKey: "transform", object: sublayer, arguments: nil) 的forKey 参数感到特别困惑。
在文档中,它是这样描述的:
动作的标识符。标识符可以是键或键路径 相对于对象、任意外部动作或其中一个 CALayer 中定义的动作标识符。
我知道渲染树中的动画列表就像一个字典,因此您使用键查询列表并获得特定动画作为值,这就是上面示例中发生的情况。子层用“moveRight”查询动画列表:
guard let action = sublayer.action(forKey: "moveRight") else {
return
}
然后通过下面的方法返回action:
func action(for layer: CALayer, forKey event: String) -> CAAction? {
guard event == "moveRight" else {
return nil
}
let animation = CABasicAnimation()
animation.valueFunction = CAValueFunction(name: kCAValueFunctionTranslateX)
animation.fromValue = 1
animation.toValue = 300
animation.duration = 2
return animation
}
但是,这个 forKey: "transform" 是干什么用的?我们已经用“moveRight”键查询了动画列表并得到了值。为什么我们需要另一个密钥?
另外,如果我要创建一个结合变换和不透明度或其他非变换属性的组动画怎么办?我必须使用什么来代替 forKey: "transform"?
【问题讨论】:
标签: ios swift calayer cabasicanimation