Search code examples
iosuiviewkey-value-observing

UIView KVO: Why don't changes to "center" cause KVO notifications for "frame"?


I'm trying to deepen my understanding of these mechanisms. I have a UIView that is touch enabled, and can update its own center property.

My understanding is that the frame property is a synthesized function of the center and bounds. Assuming that this is true, I put an observer on my touchable/movable view which observed its frame property. But that observer is never notified about the changes to frame (which happen automatically when center is changed). If I observe center directly, it works as expected.

Why doesn't observing frame work here?


Note that I know that I could be just observing center directly, which is fine. I can also surround the change to center with will/did methods for frame, which then also works:

[self willChangeValueForKey:@"frame"];
[self setCenter:center];
[self didChangeValueForKey:@"frame"];

But I mainly just want to understand why it doesn't work out of the box the way I expect it to work, in case I'm missing something conceptually here, either about KVO or about the view geometry.

Thanks.


Solution

  • The main reason observing frame isn't working is because no UIKit property is defined to be KVO-compliant unless explicitly documented to be KVO-compliant.

    You're not missing anything - Unfortunately UIKit doesn't support what you're trying to do with the observation.