简体   繁体   中英

Change image on button when I pressed other button on iPhone

In IB I create 9 buttons (custom) and a select for State config: selected (button1.png) disabled (button1_disabled.png).....(button9_disabled.png)

this tip if only when select button and unselected button

- (IBAction)onButtonsTapped:(UIButton*)sender {
    [[sender setSelected:![sender isSelected]];
    [priviousSelectedBtn setSelected:NO];
}

but i want to release that:

When I press button 1 (action) change the picture on the button 1 (setSelected: YES)

I press the button 2 (action) change the picture on the button 2 (setSelected: YES) and change the image on the number 1 (setSelected: NO)

I press the button 9 (action) change the image on the button 9 (setSelected: YES) and change the image on the button 2 (setSelected: NO)

You can create nine outlets for each button and loop through them to check and unselect. (Codes not compiler checked, you may get some idea)

Or, you can store an outlet for previousSelectedButton.

@property(strong)id previousSelectedButton;

- (IBAction)onButtonsTapped:(UIButton*)sender {
    [sender setSelected];
    [previousSelectedButton setSelected:NO];

    if(previousSelectedButton==nil || previousSelectedButton!=sender){
         previousSelectedButton=sender;
    }

}

Try the below code

for (int tag = 1; tag <= 9; tag++)//set your tag value as you wish max is 9 as you have mentioned there are 9 buttons
{
    UIButton *btn = (UIButton*)[self.view viewWithTag:tag];

    if (btn.tag != sender.tag)
    {
        [btn setSelected:NO];
    }

}

Hope this may help you. And don't reuse those tag for the superview of those button. And make a unique series of tag value for each button.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM