Reputation: 724
I need to use checkboxes (instead of UISwitch), as eventually these are going to be printed onto a sheet. I'm using the following code to initialize my check box
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];
and the following code to handle the switch
-(void)checkboxSelected:(id)sender {
if([checkbox1 isSelected]==YES) {
[checkbox1 setSelected:NO];
} else {
[checkbox1 setSelected:YES];
}
All this works perfectly fine . . . when I'm dealing with 1 checkbox . . . but if I want to have lets say 10 checkboxes on the same page - Do i need to create 10 separate methods ?
It just seems wasteful . . .. is there a better way to acheive this ?
Thank you for all your help
Upvotes: 1
Views: 3152
Reputation: 49730
you have to manage evey Button check Box withing a single Method by using tag:-
Lat say you crating 10 Buttong with ForLoop
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];
}
}
Upvotes: 1
Reputation: 170849
You can have the same method for all checkboxes. Sender parameter in your checkboxSelected method is the UIButton that triggered the action, so it will be tapped checkbox in your case:
-(void)checkboxSelected:(UIButton*)sender {
sender.selected = !sender.selected;
}
Upvotes: 4
Reputation: 1312
try this one
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];
}
and to check whether selected or not
-(void)checkboxSelect:(UIButton*)sender {
sender.selected = !sender.selected;
}
Upvotes: 1