如何在CAShapeLayer动画中使用Swift 4 KeyPath

时间:2017-08-08 09:12:49

标签: ios swift swift4

如果我编写Swift 3代码,它将如下所示:

let animation = CABasicAnimation(keyPath: #keyPath(CAShapeLayer.path))

但是我尝试为keyPath使用Swift 4新语法,我得到了:

let keyPath = \CAShapeLayer.path
let animation = CABasicAnimation(keyPath: keyPath) // error line
  

>错误:无法转换类型' ReferenceWritableKeyPath'的值预期的参数类型'字符串?'

如何使用swift 4在这种情况下使用密钥路径?

3 个答案:

答案 0 :(得分:7)

至于现在CABasicAnimation仍使用旧的String keyPaths,因此即使您使用的是Swift 4,仍应使用#keyPath(CAShapeLayer.path)

Apple将来可能会更新它的所有API,以利用这些更安全的密钥路径引用。但是现在你被“不安全”的字符串困住了。

答案 1 :(得分:0)

是的,可以使用快捷键路径。 喜欢:

extension UIView {

func animateLayer<Value>(_ keyPath: WritableKeyPath<CALayer, Value>, to value:Value, duration: CFTimeInterval) {

    let keyString = NSExpression(forKeyPath: keyPath).keyPath
    let animation = CABasicAnimation(keyPath: keyString)
    animation.fromValue = self.layer[keyPath: keyPath]
    animation.toValue = value
    animation.duration = duration
    self.layer.add(animation, forKey: animation.keyPath)
    var thelayer = layer
    thelayer[keyPath: keyPath] = value
}
}

用法类似:

animateLayer(\.shadowOffset, to: CGSize(width: 3, height: 3), duration:1)
animateLayer(\.shadowOpacity, to: 0.4, duration: 1)

尚未经过全面测试。但为我工作。

答案 2 :(得分:0)

对于Swift 5,您可以使用与此类似的内容:

[
{"name" : "one", "sports" : "cricket", "prize" : "first"},
{"name" : "one", "sports" : "cricket", "prize" : "second"},
{"name" : "one", "sports" : "football", "prize" : "first"},
{"name" : "two", "sports" : "cricket", "prize" : "first"},
{"name" : "two", "sports" : "cricket", "prize" : "second"},
{"name" : "two", "sports" : "football", "prize" : "first"},
{"name" : "three", "sports" : "cricket", "prize" : "second"},    
{"name" : "three", "sports" : "football", "prize" : "first"},    
]