How listen for UIButton state change?

DougW picture DougW · Mar 23, 2010 · Viewed 23.3k times · Source

I'm extending UIButton with generic functionality to change certain appearance attributes based on the displayed title.

In order to do this, I need to detect and respond to changes in the "state" property. This is so I make sure the appearance is adjusted properly if the user has set different titles for different states. I assumed I would need to use some sort of KVO like the following:

[self addObserver:self 
       forKeyPath:@"state" 
          options:NSKeyValueObservingOptionNew 
          context:nil];

But this does not seem to fire the observeValueForKeyPath:... method for @"state" or @"currentTitle". I assume this is because UIButton does not implement the KVO pattern for those properties.

I do not want to just listen for clicks. Those events cause a state change, but are not the only potential causes.

Does anyone know a way to listen to and respond to state changes of a UIButton?

Thanks


UPDATE

Just a note since I've learned a few things in the last couple years ;).

I've since talked with some Apple folks who know, and the reason KVO doesn't work on the state property owes to the fact that NONE of UIKit is guaranteed to be KVO compliant. Thought that was worth repeating here--if you are trying to listen to any property of a UIKit framework class, be aware that it may work but is not officially supported and could break on different iOS versions.

Answer

DougW picture DougW · Mar 23, 2010

Alright I figured out a solution that works. You can listen to the text property of the button's titleLabel.

[self.titleLabel addObserver:self 
                  forKeyPath:@"text" 
                     options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld 
                     context:nil];

It seems to get fired twice per change, so you should check to make sure that the values of @"old" and @"new" in the passed change dictionary are different.

NOTE: Don't use @"old" and @"new" directly. The constants are NSKeyValueChangeOldKey and NSKeyValueChangeNewKey respectively.