UIButton has a state property, which appears to be KVO compliant by all accounts and there is no documentation to indicate otherwise. However, when I added an observer to a UIButton's state property, the observer callback was never invoked. How come?
Key-value observing is a Cocoa programming pattern you use to notify objects about changes to properties of other objects. It's useful for communicating changes between logically separated parts of your app—such as between models and views. You can only use key-value observing with classes that inherit from NSObject .
Key-Value Observing, KVO for short, is an important concept of the Cocoa API. It allows objects to be notified when the state of another object changes.
KVO and KVC or Key-Value Observing and Key-Value Coding are mechanisms originally built and provided by Objective-C that allows us to locate and interact with the underlying properties of a class that inherits NSObject at runtime.
Key-Value-Observing (KVO) allows you to observe changes to a property or value. To observe a property using KVO you would identify to property with a string; i.e., using KVC. Therefore, the observable object must be KVC compliant. [myObject addObserver:self forKeyPath:@"foo.bar.baz" options:0 context:NULL];
If you look at the documentation of UIControl, the state property is marked: synthesized from other flags.
I guess this is why changes to this property are not KVO compliant.
However, you can simply register and observer for the values you need - highlighted, selected, enabled.
These properties are KVO compliant and you will get the observer callback when they change.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With