Search code examples
iosdelegatesuilabeltextchanged

iOS how to find out if a UILabel has changed it's text


Just had a question regarding the UILabel class. I know that the UITextField control has a delegate for when the editing has changed, but I was wondering if the UILabel has a similar field. The reason I ask is that my application queries the network for when certain pieces of information change and updates them accordingly and I don't want to hard code in my update the name of the label I want to watch for just to do a small task regarding it. If it has a delegate or something equivalent to it so that my class can monitor for this information that would be great.

If not then any advice would be greatly appreciated.


Solution

  • You can use KVO to find out or perform some code when the text changes like this :

    [somelabel addObserver:self forKeyPath:@"text" options:NSKeyValueObservingOptionNew context:NULL];
    

    and then listen for the changes like this

    - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    
        NSLog(@"the text changed");
    }