Reputation: 71
I want to create a simple checkbox in a tableview. First I create the View in the storyboard and every element get a tag in the cell. Then I coded this in Controller.m
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
...
UIButton *checkbox = (UIButton *)[cell viewWithTag:103];
checkbox.selected = NO;
[checkbox setBackgroundImage:[UIImage imageNamed:@"uCheckbox2px"] forState:UIControlStateNormal];
[checkbox addTarget:self action:@selector(changeState:) forControlEvents:UIControlEventTouchUpInside];
...
}
-(void) changeState:(UIButton *)checkbox
{
checkbox.selected = !checkbox.selected;
if (checkbox.selected)
[checkbox setBackgroundImage:[UIImage imageNamed:@"cCheckbox2px"] forState:UIControlStateSelected];
else
[checkbox setBackgroundImage:[UIImage imageNamed:@"uCheckbox2px"] forState:UIControlStateNormal];
}
But if I tap on the button the image don't change. Why is this and how I fix it? Thanks for help!
Upvotes: 0
Views: 80
Reputation: 20021
Make it like this
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
...
UIButton *checkbox = (UIButton *)[cell viewWithTag:103];
[checkbox setBackgroundImage:[UIImage imageNamed:@"uCheckbox2px"] forState:UIControlStateNormal];
[checkbox setBackgroundImage:[UIImage imageNamed:@"cCheckbox2px"] forState:UIControlStateSelected];
[checkbox addTarget:self action:@selector(changeState:) forControlEvents:UIControlEventTouchUpInside];
...
}
-(void) changeState:(UIButton *)checkbox
{
checkbox.selected = !checkbox.selected;
}
Upvotes: 1
Reputation: 6445
This is because everytime calling cellForRowAtIndexPath: checkbox.selected = NO;
will make the selected property FALSE. So after that, in the changeState:,
checkbox.selected = !checkbox.selected;
will change the selected property to TRUE. So whenever you tap the button, selected property becomes TRUE only. So move checkbox.selected = NO; to inside of if(cell == nil)
condition
Upvotes: 1
Reputation: 2127
I guess the code you have given in your button tap event is not needed. Only changing the state is enough.
if (checkbox.selected)
[checkbox setBackgroundImage:[UIImage imageNamed:@"cCheckbox2px"] forState:UIControlStateSelected];
else
[checkbox setBackgroundImage:[UIImage imageNamed:@"uCheckbox2px"] forState:UIControlStateNormal];
But you need to specify the image for both states (UIControlStateSelected
and UIControlStateNormal
) in your cellForRowAtIndexPath
.
Upvotes: 0