xcode 检测 UILabel 文本中的变化

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14326566/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 02:31:21  来源:igfitidea点击:

Detect Change in UILabel Text

iosxcodeuilabelnsnotificationcenter

提问by user717452

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.

是否可以为 UILabel 的文本属性更改设置通知?当我找不到用于 UILabel 的一个时,我尝试了用于 UITextFields 的一个,但它没有用。

 [[NSNotificationCenter defaultCenter]
 addObserver:self
 selector:@selector(posttosocial)
 name:UITextFieldTextDidChangeNotification
 object:nowplaying];

回答by

You can use key-value observing (KVO):

您可以使用键值观察(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. */
    }
}

回答by May Rest in Peace

For Swift 3.2+

对于 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.

observation.invalidate()观察完毕后调用。