How to Key-Value-Observe the rotation of a CALayer?

感情迁移 提交于 2020-01-04 05:26:14

问题


I can access the value like this:

NSNumber* rotationZ = [myLayer valueForKeyPath:@"transform.rotation.z"];

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];

The compiler tells me:

*** 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.'

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?

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?


回答1:


The transform property for the CALayer is a struct, not an object, so it isn't KVC compliant.

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.

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.



来源:https://stackoverflow.com/questions/1260704/how-to-key-value-observe-the-rotation-of-a-calayer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!