我看到很多旋转视图的代码,如下所示:
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];
(例如,this question的许多答案)
但是,当我尝试访问
self.view.layer.transform.rotation
或self.view.layer.transform.rotation.z
时,编译器会告诉我“在CATransform3D中没有名为'rotation'的成员”。 docs for CATransform3D
也不会将rotation
显示为实例属性。我的猜测是
CAAnimation
以某种方式将transform.rotation
密钥路径转换为适当的转换,但是我想知道引擎盖下到底发生了什么。这到底是怎么回事? 最佳答案
根据Key-Value Coding Extensions
核心动画扩展了NSKeyValueCoding协议,因为它与CAAnimation和CALayer类有关。此扩展为某些键添加了默认值,扩展了包装约定,并为CGPoint,CGRect,CGSize和CATransform3D类型添加了键路径支持。rotation
不是CATransform3D
的属性。它是受支持的关键路径,用于以一种便捷的方式指定要设置动画的数据结构的字段。
您还可以将这些约定与setValue:forKeyPath:和valueForKeyPath:方法结合使用来设置和获取这些字段。
使用键路径设置值与使用Objective-C属性设置值不同。您不能使用属性符号来设置变换值。您必须将setValue:forKeyPath:方法与前面的密钥路径字符串一起使用。
您可以使用setValue:forKeyPath:
,valueForKeyPath:
进行设置或获取,但不能使用属性符号。
如果您想了解实际情况,请进一步了解NSKeyValueCoding
here