开发者

iOS: Control two CheckBoxes

开发者 https://www.devze.com 2023-03-20 18:19 出处:网络
I have this code to control two check boxes (buttons customized): - (IBAction) setCheckBox: (id) sender{

I have this code to control two check boxes (buttons customized):

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

You can see that this code control two checkboxes, when I press one it become checked and when I press another time it become unchecked.

Now I want change this code in this way: In default checkbox with tag 10 is checked and when I press it, I haven't effects, but when I press checkbox with tag 11 it should be checked 开发者_开发百科and checkbox 10 should be unchecked. The checkbox should toggle the selection and also the bool value


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

you can get checkbox by tag value like I assume checkbox are instance of uibutton so

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

I hope you understand. Also set the images according to code.


If you want the behavior of radio buttons, you should probably use radio buttons instead of check boxes.

Assuming that you store your check boxes as instance variables named checkbox10 and checkbox11, this should solve your problem:

- (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];
        }
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号