Setting UITableViewCell button image values during scrolling
- by Rob
I am having an issue where I am trying to save whether a repeat image will show selected or not (it is created as a UIButton on a UITableViewCell created in IB).
The issue is that since the cell gets re-used randomly, the image gets reset or set somewhere else after you start scrolling. I've looked all over and the advice was to setup an NSMutableArray to store the button's selection state and I am doing that in an array called checkRepeatState
My question is: where do I put the if-then-else statement in the code to where it will actually change the button image based on if the checkRepeatState is set to 0 or 1 for the given cell that is coming back into view? Right now, the if-then-else statement I am using has absolutely no effect on the button image when it comes into view. I'm very confused at this point.
Thank you ahead of time for any insight you can give!!!
My code is as follows:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
// set up the cell
static NSString *CellIdentifier = @"PlayerCell";
PlayerCell *cell = (PlayerCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (!cell) {
[[NSBundle mainBundle] loadNibNamed:@"PlayerNibCells" owner:self options:nil];
cell = tmpCell;
self.tmpCell = nil;
NSLog(@"Creating a new cell");
}
// Display dark and light background in alternate rows -- see tableView:willDisplayCell:forRowAtIndexPath:.
cell.useDarkBackground = (indexPath.row % 2 == 0);
// Configure the data for the cell.
NSDictionary *dataItem = [soundCategories objectAtIndex:indexPath.row];
UILabel *label;
label = (UILabel *)[cell viewWithTag:1];
label.text = [dataItem objectForKey:@"AnimalName"];
label = (UILabel *)[cell viewWithTag:2];
label.text = [dataItem objectForKey:@"Description"];
UIImageView *img;
img = (UIImageView *)[cell viewWithTag:3];
img.image = [UIImage imageNamed:[dataItem objectForKey:@"Icon"]];
NSInteger row = indexPath.row;
NSNumber *checkValue = [checkRepeatState objectAtIndex:row];
NSLog(@"checkValue is %d", [checkValue intValue]);
// Reusing cell; make sure it has correct image based on checkRepeatState value
UIButton *repeatbutton = (UIButton *)[cell viewWithTag:4];
if ([checkValue intValue] == 1) {
NSLog(@"repeatbutton is selected");
[repeatbutton setImage:[UIImage imageNamed:@"repeatselected.png"] forState:UIControlStateSelected];
[repeatbutton setNeedsDisplay];
} else {
NSLog(@"repeatbutton is NOT selected");
[repeatbutton setImage:[UIImage imageNamed:@"repeat.png"] forState:UIControlStateNormal];
[repeatbutton setNeedsDisplay];
}
cell.accessoryType = UITableViewCellAccessoryNone;
return cell;
}