简体   繁体   中英

Xcode radio buttons- Changing background image of a button when another button is pressed

I'm trying to implement my own basic radio buttons, such that only one of them can be selected at a time. Here's the code I'm using->

- (IBAction)btn2Pressed:(UIButton *)sender {
    [btn1 setBackgroundImage:[UIImage imageNamed:@"circle-uncheck.png"] forState:UIControlStateNormal];
    btn2pressed = YES;
    btn1pressed = NO;
}


- (IBAction)btn1Pressed:(UIButton *)sender {
    [btn2 setBackgroundImage:[UIImage imageNamed:@"circle-uncheck.png"] forState:UIControlStateNormal];
    btn1pressed = YES;
    btn2pressed = NO;
}

But it's not working, ie the image of the other button isn't changing. :(

I'm not able to figure out what I'm doing wrong.

When you press any of the 2 buttons, you set the background image to circle-uncheck.png . How is it ever be changed to checked ? It will stay unchecked forever, I guess.

EDIT (due to you comment below):

If you set the background images initially in the Interface Builder, they will be changed to circle-uncheck.png as soon as a button is pushed, and they are apparently never be set to the checked state.
You had to modify your code to something like

- (IBAction)btn2Pressed:(UIButton *)sender {
    [btn1 setBackgroundImage:[UIImage imageNamed:@"circle-uncheck.png"] forState:UIControlStateNormal];
    [btn2 setBackgroundImage:[UIImage imageNamed:@"circle-check.png"] forState:UIControlStateNormal];
    btn2pressed = YES;
    btn1pressed = NO;
}

- (IBAction)btn1Pressed:(UIButton *)sender {
    [btn2 setBackgroundImage:[UIImage imageNamed:@"circle-uncheck.png"] forState:UIControlStateNormal];
    [btn1 setBackgroundImage:[UIImage imageNamed:@"circle-check.png"] forState:UIControlStateNormal];
    btn1pressed = YES;
    btn2pressed = NO;
}

If you don't wish to use a UISegmentedControl , I would create a IBOutletCollection and link all of your radio buttons to it.

@property(nonatomic, strong) IBOutletCollection(UIButton) NSArray *radioButtons;

In Interface builder I would set a selected state background image and an normal state background image.

Or in code something like:

[btn1 setBackgroundImage:[UIImage imageNamed:@"circle-uncheck.png"] forState:UIControlStateNormal];
[btn1 setBackgroundImage:[UIImage imageNamed:@"circle-check.png"] forState:UIControlStateSelected];

Then I would create one control function:

-(IBAction)didSelectRadioButton:(id)sender
{
    for(UIButton *button in self.radioButtons){
        button.selected = NO;
    }

    UIButton *selectedButton = (UIButton *)sender;
    selectedButton.selected = YES;
}

A simple radio solution using UIButtons, and scalable :)

W

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