Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to know if UIButton titlelable.text changed

I just want to know how can I fire some function when button title change ? i tried to use this command but nothing work :

[button addTarget:self 
           action:@selector(function:) 
       forControl:UIControlEventValueChange];
like image 592
user2978353 Avatar asked Feb 14 '23 13:02

user2978353


1 Answers

You can use an observer in your viewcontroller that has an outlet to the button:

  1. First add the observer (in viewDidLoad for example)

    [self.button addObserver:self 
                  forKeyPath:@"titleLabel.text" 
                     options:NSKeyValueObservingOptionNew 
                     context:NULL];
    
  2. Override default observer method on your 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;
        }
    }
    
  3. Remove yourself as observer in the dealloc function

    [self.button removeObserver:self forKeyPath:@"titleLabel.text"];
    
like image 135
Thomas Keuleers Avatar answered Feb 16 '23 04:02

Thomas Keuleers