如何键值观察CALayer的旋转? [英] How to Key-Value-Observe the rotation of a CALayer?
问题描述
我可以这样访问该值:
NSNumber* rotationZ = [myLayer valueForKeyPath:@"transform.rotation.z"];
但是由于某些原因,如果我尝试KV观察该关键路径,则会出现编译器错误.首先,这是我尝试做到的方式:
But for some reason, if I try to KV-observe that key path, I get a compiler error. First, this is how I try to do it:
[myLayer addObserver:self forKeyPath:@"transform.rotation.z" options:0 context:nil];
编译器告诉我:
***由于未捕获的异常'NSUnknownKeyException'而终止应用程序, 原因: '[ addObserver:forKeyPath:@"rotation.z" 已发送选项:0x0上下文:0x528890] 到不符合KVC的对象 旋转"属性."
*** Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[ addObserver: forKeyPath:@"rotation.z" options:0x0 context:0x528890] was sent to an object that is not KVC-compliant for the "rotation" property.'
我不明白的是,为什么我可以通过KVC密钥路径访问z值,但不向其添加观察者.这有道理吗?
what I don't get is, why I can access that z value by KVC key path, but not add an observer to it. Does this make sense?
我还能如何观察该矩阵的z值?我不在乎矩阵的其他值.仅z旋转.还有其他方式可以访问和观察它吗?
How else could I observe the z value of that matrix? I don't care about the other values of the matrix. Only the z rotation. Any other way to access and observe it?
推荐答案
CALayer
的transform
属性是结构,而不是对象,因此不符合KVC.
The transform
property for the CALayer
is a struct, not an object, so it isn't KVC compliant.
您应该能够做的是,而不是绑定到Z旋转,而是绑定到transform属性,并在每次收到KVO通知时将Z值拉出.
What you should be able to do is, instead of binding to the Z rotation, bind to the transform property and pull the Z value out whenever you get the KVO notification.
我认为这里的困惑在于,当您在NSObject上使用点表示法时,您实际上是在使用该对象的- (id)property
和- (void)setProperty
方法,这些方法与KVC兼容.在结构上使用点表示法时,就是在访问该结构的成员,而不是调用方法.
I think the confusion here is that when you use dot notation on an NSObject, you're really using that object's - (id)property
and - (void)setProperty
methods, which are KVC compliant. When you use dot notation on a struct, you're accessing a member of that struct, not calling a method.
这篇关于如何键值观察CALayer的旋转?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!