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

2019-07-12 13:42发布

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条回答
不美不萌又怎样
2楼-- · 2019-07-12 14:13

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.

查看更多
登录 后发表回答