I want to change a specific UIImageView
inside a UITableViewCell
with this:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
[self.tableView beginUpdates];
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
UYLTextCell *textCell = (UYLTextCell *)cell;
textCell.selected = YES;
//get and show the image at selected cell
textCell.testImage.image = [UIImage imageNamed:@"image280280.jpg"];
//[tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
[self.tableView endUpdates];
}
But what happened is some cell had their image View even though it has not been clicked.
Table views re-use cells. When a cell is scrolled offscreen it is added to a queue, and will be re-used for the next cell to be scrolled onscreen. That means your cell configuration code in
tableView:cellForRowAtIndexPath:
should be enough to properly configure any cell, including cells that were previously selected at a different indexPath. IntableView:didSelectRowAtIndexPath:
store the selected index path in a property and use that property to configure your cell intableView:cellForRowAtIndexPath:
. The image will need to be set intableView:cellForRowAtIndexPath:
whether the cell is selected or not (unless you implementprepareForReuse
in your custom cell).