0

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

- (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 应该被取消选中。复选框应切换选择以及布尔值

4

2 回答 2

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

我希望你明白。还要根据代码设置图像。

于 2011-07-14T10:45:35.343 回答
0

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

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

- (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];
        }
    }
}
于 2011-07-14T10:52:03.973 回答