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

安稳与你 提交于 2020-01-06 10:53:27

问题


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.


回答1:


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



回答2:


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



来源:https://stackoverflow.com/questions/24088024/xcode-radio-buttons-changing-background-image-of-a-button-when-another-button-i

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!