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
Detect Change in UILabel Text
提问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()
观察完毕后调用。