Detect Change in UILabel Text
Asked Answered
T

2

9

Is it possible to set a Notification for when a UILabel's text property is changed? I tried the one used for UITextFields when I couldn't find one for a UILabel, but it didn't work.

 [[NSNotificationCenter defaultCenter]
 addObserver:self
 selector:@selector(posttosocial)
 name:UITextFieldTextDidChangeNotification
 object:nowplaying];
Tortuga answered 14/1, 2013 at 21:0 Comment(6)
Try using key-value observing.Obmutescence
How would I go about that for a UILabel?Tortuga
@userXXXX [label addObserver:self forKeyPath:@"text" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:NULL]; then implement the appropriate observer methods on self.Obmutescence
^Do you have to set a delegate / are frameworks required for that method?Flattop
@H2CO3 Thanks! If you could put that down as an answer, I'll accept that! No framework really required outside of basic. Just use this method - (void) observeValueForKeyPath:(NSString*)keyPath ofObject:(id)object change:(NSDictionary*)change context:(void*)context { if ([keyPath isEqualToString:@"text"]) { and put the code he added in your viewDidLoadTortuga
@Tortuga No problem, I've made this an answer. Enjoy coding!Obmutescence
O
23

You can use key-value observing (KVO):

[label addObserver:self
        forKeyPath:@"text"
           options:NSKeyValueObservingOptionNew
                 | NSKeyValueObservingOptionOld
           context:NULL];

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    if ([keyPath isEqualToString:@"text"]) {
        /* etc. */
    }
}
Obmutescence answered 14/1, 2013 at 22:2 Comment(0)
P
0

For Swift 3.2+

let observation = label.observe(\UILabel.text, options: [.new, .old]) { label, change in
        print("\(change.newValue as? String ?? "" )")
    }

Call observation.invalidate() when done observing.

Poulard answered 6/8, 2019 at 9:4 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.