iOS:控制两个CheckBoxes

时间:2011-07-14 10:37:02

标签: objective-c ios checkbox uibutton sender

我有这个代码来控制两个复选框(自定义按钮):

- (IBAction) setCheckBox: (id) sender{

    UIImage *selected = [UIImage imageNamed:@"checkbox_checked.png"];
    UIImage *notSelected = [UIImage imageNamed:@"checkbox_unchecked.png"];

    if ([sender isSelected]) 
    {  
        [sender setImage:notSelected forState:UIControlStateNormal];  
        [sender setSelected:NO];  
        if ([sender tag] == 10) boolOne = FALSE;
        if ([sender tag] == 11) boolTwo = FALSE;
    }
    else 
    {     
        [sender setImage:selected forState:UIControlStateSelected]; 
        [sender setSelected:YES];
        if ([sender tag] == 10) boolOne = TRUE;
        if ([sender tag] == 11) boolTwo = TRUE;
    }
}

你可以看到这段代码控制了两个复选框,当我按下一个复选框时,它会被检查,当我按下另一个时,它会被取消选中。

现在我想以这种方式更改此代码: 在默认复选框中,标签10被选中,当我按下它时,我没有效果,但是当我按下带有标签11的复选框时,应该选中它并且应该取消选中复选框10。 复选框应切换选择以及bool值

2 个答案:

答案 0 :(得分:1)

if([sender isSelected])
 return;
if([sender tag] == 11){
  [sender setSelected:YES];
 [checkbox10 setSelected:NO];
}
if ([sender tag] == 10) {
 [sender setSelected:YES];
 [checkbox11 setSelected:NO];
}

你可以按标签值获取复选框,就像我假设复选框是uibutton的实例所以

UIButton *checkBox10 = (UIButton*)[self.view viewWithTag:10]; 

我希望你理解。还可以根据代码设置图像。

答案 1 :(得分:0)

如果您想要单选按钮的行为,您应该使用单选按钮而不是复选框。

假设您将复选框存储为名为checkbox10checkbox11的实例变量,这可以解决您的问题:

- (IBAction) setCheckBox: (id) sender{

    UIImage *selected = [UIImage imageNamed:@"checkbox_checked.png"];
    UIImage *notSelected = [UIImage imageNamed:@"checkbox_unchecked.png"];

    if (![sender isSelected]) 
    {  
        [sender setImage:notSelected forState:UIControlStateNormal];  
        [sender setSelected:YES];
        if ([sender tag] == 10)
        {
            boolOne = YES;
            boolTwo = NO;
            [checkbox11 setImage:notSelected forState:UIControlStateNormal];  
            [checkbox11 setSelected:NO];
        }
        if ([sender tag] == 11)
        {
            boolTwo = YES;
            boolOne = NO;
            [checkbox10 setImage:notSelected forState:UIControlStateNormal];  
            [checkbox10 setSelected:NO];
        }
    }
}