ios中的单选按钮选择图像

时间:2013-11-29 05:57:59

标签: objective-c uibutton ibaction

您好我在我的应用中使用按钮作为单选按钮。应用程序有两个按钮作为男性和女性一旦使用选择男性其图像变为绿色如果再选择其图像灰色。同样的女性按钮正在发生。这项工作很好。但是,当我被选中男性然后我选择女性然后男性按钮chage到灰色coz,你可以选择只有性别。 我的问题是当我选择男性然后选择女性男性按钮图像正在徘徊但如果用户想要设置性别男性它需要按两次???

-(IBAction)selectMale:(id) sender{ // MALE BUTTON
UIButton *RadioButton1 = (UIButton*)sender;
[self radiobuttonAction:RadioButton1];
}

-(void)radiobuttonAction:(UIButton *)Button
{
if(![Button isSelected])
{
    [Button setSelected:YES];
    [Button setImage:[UIImage imageNamed:@"radio_active.png"] forState:UIControlStateSelected];
    gender = @"Male";
    [btnFemale setImage:[UIImage imageNamed:@"radio.png"] forState:UIControlStateSelected];

}
else
{
    [Button setSelected:NO];
    [Button setImage:[UIImage imageNamed:@"radio.png"] forState:UIControlStateNormal];
}
 }

-(IBAction)selectFemale:(id) sender{
UIButton *RadioButton1 = (UIButton*)sender;
[self radiobuttonActionFemale:RadioButton1];
 }
-(void)radiobuttonActionFemale:(UIButton *)Button
{
if(![Button isSelected])
{
    [Button setSelected:YES];
    [Button setImage:[UIImage imageNamed:@"radio_active.png"] forState:UIControlStateSelected];
    gender = @"Female";
    [btnMale setImage:[UIImage imageNamed:@"radio.png"] forState:UIControlStateSelected];
}
else
{
    [Button setSelected:NO];
    [Button setImage:[UIImage imageNamed:@"radio.png"] forState:UIControlStateNormal];

}
}

3 个答案:

答案 0 :(得分:1)

radiobuttonAction方法中,在if条件中最后添加行:

[btnFemale setSelected:NO];

radiobuttonActionFemale方法中,在if条件中最后添加一行:

[btnMale setSelected:NO];

答案 1 :(得分:0)

尝试重置异性(例如,在按下btnMale时重置btnFemale)单选按钮,然后再设置新的性别..

答案 2 :(得分:0)

尝试这种方法。将所有按钮(男性和女性)添加到数组和按钮操作处理程序更改按钮状态:

- (void) buttonPressed:(UIButton *)sender
{
for (UIButton *button in self.buttonsArray) {
    if([button isKindOfClass:[UIButton class]]){
        button.selected = (button.state & sender.state);
    }
}