I’m making a simple “Add to favorites” feature which is a UITableViewController. When the user selected a cell, I set the color on gray and disable the selectionStyle
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
cell.textLabel.textColor = [UIColor grayColor];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
}
My first problem was that everytime I was selecting a cell, some others cells was switching color too. So I deleted the following code for making this not happening :
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
But I still have a strange problem : after scrolling down the tableview and then get back to the top of it, I notice that all the cells I’ve selected were back to the default color, and the last cell selected is highlighted in blue.
So I’m maybe wrong but I’m supposing that the tableview is refreshing when scrolling and I want to disable this behavior.
Thanks in advance for your help.
You’re missing a fundamental understanding of the way a UITableView presents its subviews (UITableViewCells). I would suggest reading the UITableView programming guide. Never remove the
dequeueReusableCellWithIdentifiercall on the table view, this is very important for performance.For your problem: you need to keep track of the state of each cell, and set the state of selection in cellForRowAtIndexPath:, the UITableView reuses cells whenever it can, and refreshes cells when they are scrolled on and off screen.
A very simple implementation would be:
and in cellForRow