Keeping the UIButton button pressed (selected / highlighted state) until another button is pressed?

I have 3 buttons at the bottom of my view controller, btn1 btn2 btn3, I use them instead of the tab bar, since it is not possible to fully customize the tab bar to suit my requirements.

Now the problem is that when btn1 is pressed, I want it to change its image to a gray rectangle instead of the usual state image. I set the images for both states on output I declared for the btn1Outlet button using the setimage and uicontrolstate properties of the output.

The problem is that I cannot hold the button until neither btn2 nor btn3 is pressed. btn alone changes to the selected state image only as long as it is pressed, the moment I leave it, it returns to its normal state.

How to save the btn1 image in the selected image until either of the two buttons is pressed?

+5
source share
3 answers

What you did sets the image for the “Selected” state, so when you click it, you can see your image.

What you want to do is

1) set the image to SELECTED state

2) ( ), ( , )

3) :

button.selected = !button.selected;

(, , )

+4

:

  • 3 .
  • 3
  • ,
  • 2

    - (IBAction)buttonPressed:(id)sender
    {
        NSArray* buttons = [NSArray arrayWithObjects:btn1, btn2, btn3, nil];
        for (UIButton* button in buttons) {
            if (button == sender) {
                button.selected = YES;
            }
            else {
                button.selected = NO;
            }
        }
    }
    

, .

!

+2

, setSelected: YES , . :

- (void) methodThatYourButtonCalls: (id) sender {
        [self performSelector:@selector(flipButton:) withObject:sender afterDelay:0.0];


}

- (void) flipButton:(UIButton*) button {
    if(button.selected) 
        [button setSelected:NO];
    else
        [button setSelected:YES];

}

, performSelector: , [sender setSelected: YES], , !

To force the buttons to deselect when another button is pressed, I suggest adding an instance variable containing a pointer to the currently selected button, so when the new one touches, you can call flipButton: deselect the old one accordingly. So now your code should read:

add a pointer to your interface

@interface YourViewController : UIViewController
{
    UIButton *currentlySelectedButton;
}

and these methods for your implementation

- (void) methodThatYourButtonCalls: (id) sender {
    UIButton *touchedButton = (UIButton*) sender;

    //select the touched button 
    [self performSelector:@selector(flipButton:) withObject:sender afterDelay:0.0]; 

    if(currentlySelectedButton != nil) { //check to see if a button is selected...
        [self flipButton:currentlySelectedButton];

    currentlySelectedButton = touchedButton;
}

- (void) flipButton:(UIButton*) button {
    if(button.selected) 
        [button setSelected:NO];
    else
        [button setSelected:YES];

}
+1
source

All Articles