ios - 如何知道 UIButton titlerable.text 是否改变

标签 ios objective-c iphone uibutton key-value-observing

我只想知道如何在按钮标题更改时触发某些功能? 我尝试使用此命令但没有任何效果:

[button addTarget:self 
           action:@selector(function:) 
       forControl:UIControlEventValueChange];

最佳答案

你可以在你的 viewcontroller 中使用一个观察者,它有一个按钮的导出:

  1. 首先添加观察者(以viewDidLoad为例)

    [self.button addObserver:self 
                  forKeyPath:@"titleLabel.text" 
                     options:NSKeyValueObservingOptionNew 
                     context:NULL];
    
  2. 覆盖 View Controller 上的默认观察者方法

    - (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;
        }
    }
    
  3. 在 dealloc 函数中移除自己作为观察者

    [self.button removeObserver:self forKeyPath:@"titleLabel.text"];
    

关于ios - 如何知道 UIButton titlerable.text 是否改变,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22295315/

相关文章:

iOS : Audio is missing in exported video

iphone - 获取包含 UITouch 的所有点

ios - CAL层裁剪

ios - UIViewController View 错误

iphone - 让 iPhone 5 布局完全独立

iphone - iPhone 游戏的免费音效

ios - RACDisposable 在 NSURLSessionDownloadTask 完成之前被拆除

ios - 在 SWIFT 中转换 ObjectiveC 表达式

iphone - 无法在 cocos2d 中使用导入的类方法

objective-c - objective c 在异步 https 请求时检查服务器证书