Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to keep UIButton in selected state after TouchUpInside Event

I have the need for an UIButton to maintain a pressed state. Basically, if a button is in a normal state, I want to touch the button, it highlight to its standard blue color and then stay blue after lifting my finger. I made the following UIAction and connected the buttons Touch Up Inside event to it.

-(IBAction) emergencyButtonPress:(id) sender
{
    if(emergencyButton.highlighted)
    {
        emergencyButton.selected = NO;
        emergencyButton.highlighted = NO;
    }
    else
    {
        emergencyButton.selected = YES;
        emergencyButton.highlighted = YES;
    }
}

But what happens, after I remove my finger, the button goes back to a white background. For a test I added a UISwitch and have it execute the same code:

-(IBAction) emergencySwitchClick:(id) sender
{
    if(emergencyButton.highlighted)
    {
        emergencyButton.selected = NO;
        emergencyButton.highlighted = NO;
    }
    else
    {
        emergencyButton.selected = YES;
        emergencyButton.highlighted = YES;
    }
}

In this case the button toggles to a highlighted and non-highlighted state as I would expect.

Is there another event happening after the Touch Up Inside event that is resetting the state back to 'normal'? How do I maintain the highlighted state?

like image 825
WolfpackEE Avatar asked Jan 11 '12 14:01

WolfpackEE


2 Answers

The highlighted state is applied and removed by iOS when you touch / release the button. So don't depend on it in your action method.

As one of the other answers says, set the highlighted image to be the same as the selected image, and then modify your action method:

-(IBAction) emergencyButtonPress:(id) sender 
{
    emergencyButton.selected = !emergencyButton.selected;     
} 
like image 164
jrturton Avatar answered Nov 14 '22 23:11

jrturton


If you want something like a toggle button, customize your "selected" state to be your "pressed" state, and then write something like this:

- (IBAction)buttonTapped:(id)sender {
    [(UIButton*)sender setSelected:![sender isSelected]];
}
like image 20
phi Avatar answered Nov 14 '22 21:11

phi