2

I see a lot of code that rotates a view as follows:

CABasicAnimation *centerToRightRotate
    = [CABasicAnimation animationWithKeyPath:@"transform.rotation"];
centerToRightRotate.fromValue = @(0);
centerToRightRotate.toValue = @(M_PI/8);
centerToRightRotate.duration = 0.15;

[self.view.layer addAnimation:centerToRightRotate forKey:nil];

(for example, many of the answers to this question)

However, when I try to access self.view.layer.transform.rotation or self.view.layer.transform.rotation.z, the compiler will tell me "No member named 'rotation' in CATransform3D". The docs for CATransform3D also does not show rotation as an instance property.

My guess is CAAnimation is somehow translating the transform.rotation key path into the appropriate transformation, but I want to know what is actually going on under the hood. What exactly is going on here?

peco
  • 1,411
  • 3
  • 17
  • 38

1 Answers1

3

According to Key-Value Coding Extensions

Core Animation extends the NSKeyValueCoding protocol as it pertains to the CAAnimation and CALayer classes. This extension adds default values for some keys, expands wrapping conventions, and adds key path support for CGPoint, CGRect, CGSize, and CATransform3D types.

rotation isn't a property of CATransform3D. It's supported key path to specify the field of a data structure that you want to animate with a convenient way.

You can also use these conventions in conjunction with the setValue:forKeyPath: and valueForKeyPath: methods to set and get those fields.

Setting values using key paths is not the same as setting them using Objective-C properties. You cannot use property notation to set transform values. You must use the setValue:forKeyPath: method with the preceding key path strings.

You can use setValue:forKeyPath:, valueForKeyPath: to set or get it but can't use property notation.

If you want to know what is actually going on under the hood, learn more about NSKeyValueCoding here

Community
  • 1
  • 1
trungduc
  • 11,926
  • 4
  • 31
  • 55