Monis Manzoor
Monis Manzoor

Reputation: 183

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.

Upvotes: 0

Views: 330

Answers (3)

Rahul
Rahul

Reputation: 187

Instead of making two conditions

f([urlresponse status code] == 200) 
{
[myButton setTitle:@"Unfollow" forState:UIControlStateNormal]; //title changed 

[myButton addTarget:self action:@selector(unfollowButtonPressed:) forControlEvents:UIControlEventTouchUpInside];

} 

It might be helpful for your case.

Upvotes: 0

Paul.s
Paul.s

Reputation: 38728

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 {

    }
}

Upvotes: 1

Ilker Baltaci
Ilker Baltaci

Reputation: 11789

if you assign two actions for the same button for control state touchupinside, it will always trigger both.You should remove the first action while adding the second and remove second itself and add the first again at the end of selector function.

The following is the default action of the button;

[button addTarget:self:action:@selector(actionOne)forControlEvents:UIControlStateTouchUpInside]

In the actionOne you can call remove observer for the first action and add the second one.

    [button addTarget:self:action:@selector(actionTwo)forControlEvents:UIControlStateTouchUpInside]

And in actionTwo function you do the reverse

Upvotes: 0

Related Questions