use*_*353 4 iphone objective-c key-value-observing uibutton ios
我只是想知道当按钮标题改变时如何触发某些功能?我试图使用此命令,但没有任何工作:
[button addTarget:self
action:@selector(function:)
forControl:UIControlEventValueChange];
Run Code Online (Sandbox Code Playgroud)
您可以在viewcontroller中使用具有按钮插座的观察者:
首先添加观察者(例如在viewDidLoad中)
[self.button addObserver:self
forKeyPath:@"titleLabel.text"
options:NSKeyValueObservingOptionNew
context:NULL];
Run Code Online (Sandbox Code Playgroud)覆盖viewcontroller上的默认观察者方法
- (void)observeValueForKeyPath:(NSString *)keyPath
ofObject:(id)object
change:(NSDictionary *)change
context:(void *)context {
if ([keyPath isEqualToString:@"titleLabel.text"]) {
// Value changed
UIButton *button = object;
NSString *title = button.titleLabel.text;
}
}
Run Code Online (Sandbox Code Playgroud)在dealloc函数中以观察者身份移除自己
[self.button removeObserver:self forKeyPath:@"titleLabel.text"];
Run Code Online (Sandbox Code Playgroud)| 归档时间: |
|
| 查看次数: |
1437 次 |
| 最近记录: |