Search code examples
iosuibuttonuicontrol

UIButton UIControl target action 2 actions for single button


I have a button that has a selected and non-selected state.

My target action code for the button is this:

NSArray *targets = [myButton actionsForTarget:self forControlEvent:UIControlEventTouchUpInside];

    if ([targets count] == 0) {
        [myButton addTarget:self action:@selector(save:) forControlEvents:UIControlEventTouchUpInside];

When the button is pressed, it goes to selected state in the method.

If the button is selected, a different action should be called. Is there any unintended consequence to doing it this way or is there a way to add actions with UIControlState instead?

if (myButton.selected == NO){
[myButton addTarget:self action:@selector(save:) forControlEvents:UIControlEventTouchUpInside];
}
else{
[myButton addTarget:self action:@selector(delete:) forControlEvent:UIControlEventTouchUpInside];
}

Solution

  • -(IBAction)myButton:(id)sender
    {
    UIButton *btn = (UIButton*)sender;
    btn.selected = !btn.selected;
    if(btn.selected)
    {
        //Do whatever you want when button is selected
        [self delete];
    }
     else
    {
        //Do whatever you want when button isDeselected
         [self save];
    }
    }