Search code examples
iphoneios5xcode4uibuttontitle

Button triggers two actions while pressing the changed button title


I have changed button title of a UIButton programmatically. I have also assigned an action to changed button title. Now when i tap on the button, it triggers both the action (one with same button title and one with changed). However, i want to trigger only one action for the changed title button.

How can i do it? Any help would be appreciated.


Solution

  • Two solutions. Toggle the target/action between methods or decide what to do based on some state.

    1.

    - (void)method1:(id)sender;
    {
      [sender removeTarget:nil action:NULL forControlEvents:UIControlEventTouchUpInside];
      [sender addTarget:self action:@selector(method2:) forControlEvents:UIControlEventTouchUpInside];
    }
    
    - (void)method2:(id)sender;
    {
      [sender removeTarget:nil action:NULL forControlEvents:UIControlEventTouchUpInside];
      [sender addTarget:self action:@selector(method1:) forControlEvents:UIControlEventTouchUpInside];
    }
    

    2a.

    - (void)buttonTapped;
    {
      if (self.someState) {
    
      } else {
    
      }
    }
    

    2b.

    - (void)buttonTapped:(UIButton *)button;
    {
        if ([[button titleForState:UIControlStateNormal] isEqualToString:@"First title"]) {
    
        } else {
    
        }
    }