Zaxter
Zaxter

Reputation: 3033

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, i.e. the image of the other button isn't changing. :(

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

Upvotes: 0

Views: 1186

Answers (2)

William George
William George

Reputation: 6785

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

Upvotes: 0

Reinhard Männer
Reinhard Männer

Reputation: 15227

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;
}

Upvotes: 1

Related Questions