Image changed randomly in table view cell

375 Views Asked by At

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.

1

There are 1 best solutions below

4
On BEST ANSWER

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. In tableView:didSelectRowAtIndexPath: store the selected index path in a property and use that property to configure your cell in tableView:cellForRowAtIndexPath:. The image will need to be set in tableView:cellForRowAtIndexPath: whether the cell is selected or not (unless you implement prepareForReuse in your custom cell).