如何实现单选按钮的行为?

时间:2011-09-01 09:38:58

标签: iphone objective-c ios ios4

我有两个UIButton。它们的行为类似于复选框(两个按钮都可以一次选择)。但我希望一次只能选择一个按钮(如单选按钮)。我该怎么做? 这是我如何实现复选框按钮功能。

if ([btnAnswer1 isSelected]) {
        [btnAnswer1 setBackgroundImage:[UIImage imageNamed:@"checkbox_unchecked.png"] forState:UIControlStateNormal];
        [btnAnswer1 setSelected:NO];

    }else {
        [btnAnswer1 setBackgroundImage:[UIImage imageNamed:@"checked.png"] forState:UIControlStateSelected];
        [btnAnswer1 setSelected:YES];
    }



    if ([btnAnswer2 isSelected]) {
        [btnAnswer2 setBackgroundImage:[UIImage imageNamed:@"checkbox_unchecked.png"] forState:UIControlStateNormal];
        [btnAnswer2 setSelected:NO];
    }else {
        [btnAnswer2 setBackgroundImage:[UIImage imageNamed:@"checked.png"] forState:UIControlStateSelected];
        [btnAnswer2 setSelected:YES];
    }

2 个答案:

答案 0 :(得分:2)

我通常使用单选按钮的方式是:

-(void) radioButtonWasSelected:(RadioButton*) which
{
    //set all radio buttons to unselected
    //set 'which' to selected

    //do something with 'which'

}

答案 1 :(得分:1)

虽然我没有检查,但只需尝试使用给定的修改代码。

    if ([btnAnswer1 isSelected]) 
    {
        [btnAnswer1 setBackgroundImage:[UIImage imageNamed:@"checkbox_unchecked.png"] forState:UIControlStateNormal];
        [btnAnswer1 setSelected:NO];
        selected = FALSE;
        [btnAnswer2 setBackgroundImage:[UIImage imageNamed:@"checked.png"] forState :UIControlStateSelected];
        [btnAnswer2 setSelected:YES];
    }
    else 
    {
        [btnAnswer1 setBackgroundImage:[UIImage imageNamed:@"checked.png"] forState: UIControlStateSelected];
        [btnAnswer1 setSelected:YES];
        [btnAnswer2 setBackgroundImage:[UIImage imageNamed:@"checkbox_unchecked.png"] forState: UIControlStateNormal];
        [btnAnswer2 setSelected:NO];
        selected = TRUE;
    }

    if ([btnAnswer2 isSelected]) 
    {
        [btnAnswer2 setBackgroundImage:[UIImage imageNamed:@"checkbox_unchecked.png"] forState: UIControlStateNormal];
        [btnAnswer2 setSelected:NO];
        [btnAnswer1 setBackgroundImage:[UIImage imageNamed:@"checked.png"] forState: UIControlStateSelected];
        [btnAnswer1 setSelected:YES];
    }
    else 
    {
        [btnAnswer2 setBackgroundImage:[UIImage imageNamed:@"checked.png"] forState: UIControlStateSelected];
        [btnAnswer2 setSelected:YES];
        [btnAnswer1 setBackgroundImage:[UIImage imageNamed:@"checkbox_unchecked.png"] forState: UIControlStateNormal];
        [btnAnswer1 setSelected:NO];
    }