1

我需要使用复选框(而不是 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 个单独的方法吗?

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

谢谢你的帮助

4

3 回答 3

4

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

-(void)checkboxSelected:(UIButton*)sender {
    sender.selected = !sender.selected;
}
于 2013-08-14T13:02:52.640 回答
1

您必须使用标签使用单个方法管理每个按钮复选框:-

Lat 说你用 ForLoop 装了 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];

    }
} 
于 2013-08-14T13:02:00.720 回答
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;
}
于 2013-08-14T13:02:45.507 回答