8

Is it possible to use enhanced key path (as described here) for a CATransform3D property in Swift 3 with new #keyPath keyword?

In other words to replace

let scaleAnimation = CABasicAnimation(keyPath: "transform.scale")

with something like

let scaleAnimation = CABasicAnimation(keyPath:  #keyPath(CALayer.transform.???))
Radek
  • 581
  • 4
  • 12

1 Answers1

17

CAValueFunction should be used.

let scaleAnimation = CABasicAnimation(keyPath: "transform.scale")

->

let scaleAnimation = CABasicAnimation(keyPath: #keyPath(CALayer.transform))
scaleAnimation.valueFunction = CAValueFunction(name: kCAValueFunctionScale)

and

let rotationAnimation = CABasicAnimation(keyPath: "transform.rotation")

->

let rotationAnimation = CABasicAnimation(keyPath: #keyPath(CALayer.transform))
rotationAnimation.valueFunction = CAValueFunction(name: kCAValueFunctionRotateZ)

etc.

  • rotation.x -> kCAValueFunctionRotateX
  • rotation.y -> kCAValueFunctionRotateY
  • rotation.z -> kCAValueFunctionRotateZ
  • rotation -> kCAValueFunctionRotateZ
  • scale.x -> kCAValueFunctionScaleX
  • scale.y -> kCAValueFunctionScaleY
  • scale.z -> kCAValueFunctionScaleZ
  • scale -> kCAValueFunctionScale
  • translation.x -> kCAValueFunctionTranslateX
  • translation.y -> kCAValueFunctionTranslateY
  • translation.z -> kCAValueFunctionTranslateZ
  • translation -> kCAValueFunctionTranslate
JMI
  • 2,530
  • 15
  • 26
  • 1
    you said it doesn't work well for you, but it seems to work great for me! I had a `CABasicAnimation(keyPath: "transform.rotation")` and now I have this in Swift 4.2: `let animation = CABasicAnimation(keyPath: #keyPath(CALayer.transform)); animation.valueFunction = CAValueFunction(name: CAValueFunctionName.rotateZ)` – Gobe Oct 04 '18 at 16:13
  • @gobe It is quite a long time (almost 2 years). That's great news. I will update my comment. Thank you. – JMI Oct 05 '18 at 07:17
  • 1
    Hi. Any idea why this wouldn't work with `CASpringAnimation`? When I use `let animation = CASpringAnimation(keyPath: "transform.scale")`, it works fine, but if replaced with `let animation = CASpringAnimation(keyPath: #keyPath(CALayer.transform)); animation.valueFunction = CAValueFunction(name: CAValueFunctionName.scale)`, the animation simply doesn't run. – TheNeil May 02 '19 at 01:27