iOS - 处理多个复选框

时间:2013-08-14 12:58:36

标签: ios objective-c checkbox uibutton

我需要使用复选框(而不是UISwitch),因为最终会将这些复选框打印到工作表上。我正在使用以下代码初始化我的复选框

checkbox1 = [[UIButton alloc] initWithFrame:CGRectMake(40, 226.5, 134, 20)];
[checkbox1 setBackgroundImage:[UIImage imageNamed:@"unchecked.png"] forState:UIControlStateNormal];
[checkbox1 setBackgroundImage:[UIImage imageNamed:@"checked.png"] forState:UIControlStateSelected];
[checkbox1 addTarget:self action:@selector(checkboxSelected:) forControlEvents:UIControlEventTouchUpInside];
[self addSubview:checkbox1];

和以下代码来处理交换机

-(void)checkboxSelected:(id)sender {

if([checkbox1 isSelected]==YES) {
    [checkbox1 setSelected:NO];
} else {
    [checkbox1 setSelected:YES];
}

这一切都很完美。 。 。当我正在处理1个复选框时。 。 。但如果我想在同一页面上说10个复选框 - 我是否需要创建10个单独的方法?

这看起来很浪费。 。 ..有没有更好的方法来实现这一点?

感谢您的帮助

3 个答案:

答案 0 :(得分:4)

您可以为所有复选框使用相同的方法。 checkboxSelected方法中的Sender参数是触发操作的UIButton,因此在您的情况下将点击复选框:

-(void)checkboxSelected:(UIButton*)sender {
    sender.selected = !sender.selected;
}

答案 1 :(得分:1)

您必须使用标记在单个方法中管理evey Button复选框: -

Lat说你装10循环的按钮

for(i=0;i<10;i++)
{
checkbox1 = [[UIButton alloc] initWithFrame:CGRectMake(40, 226.5, 134, 20)];
[checkbox1 setBackgroundImage:[UIImage imageNamed:@"unchecked.png"] forState:UIControlStateNormal];
[checkbox1 setBackgroundImage:[UIImage imageNamed:@"checked.png"] forState:UIControlStateSelected];
checkbox1.tag=i;
[checkbox1 setSelected:NO];
[checkbox1 addTarget:self action:@selector(checkboxSelected:) forControlEvents:UIControlEventTouchUpInside];
[self addSubview:checkbox1];
}

-(void)checkboxSelected:(UIButton*)sender {
     UIButton *btnPly = (UIButton *)sender;
    if([btnPly isSelected]==YES) {
        [btnPly setBackgroundImage:[UIImage imageNamed:@"unchecked.png"] forState:UIControlStateNormal];
        [btnPly setSelected:NO];
    } else {
        [btnPly setSelected:YES];
        [btnPly setBackgroundImage:[UIImage imageNamed:@"checked.png"] forState:UIControlStateSelected];

    }
} 

答案 2 :(得分:1)

尝试这个

for(i=0;i<10;i++)
{
HTN = [[UIButton alloc] initWithFrame:CGRectMake(40, 226.5, 134, 20)];
[HTN setBackgroundImage:[UIImage imageNamed:@"unchecked.png"] forState:UIControlStateNormal];
[HTN setBackgroundImage:[UIImage imageNamed:@"checked.png"] forState:UIControlStateSelected];
HTN.tag=i;
[HTN addTarget:self action:@selector(checkboxSelect:) forControlEvents:UIControlEventTouchUpInside];
[self addSubview:checkbox1];
}

并检查是否选中

-(void)checkboxSelect:(UIButton*)sender {
    sender.selected = !sender.selected;
}