Question

  1. The code below works when I want to highlight and put a check mark next to the selected cell.

  2. It also works when I want to select another cell as it deselects the last cell or highlight and puts a check mark and highlight next to the new selected cell.

  3. It also work when I reselect a selected cell as it deselects it leaving no check mark and highlight in the UITable.

  4. However, when I select the the same cell for the third time (meaning, I first selected it, the code highlighted it and put a checkmark next it. I selected the same cell the 2nd time, and it removed the highlight and the checkmark, it is now the third time I'm selecting the same cell) it highlights the cell for a fraction of a second and than the highlight disappears. The checkmark next to the cell also never shows up as if I had just deselected it. No matter how many times I select the same cell, it does not highlight it or put a check mark next to it. The only way to accomplish this is to select another cell first, and then reselect the original cell. Please help.

    - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath*)indexPath
    {
    
        // select new
    
        UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
    
        cell.accessoryType = UITableViewCellAccessoryCheckmark;
        [cell setSelected:TRUE animated:TRUE];
    
        // deselect old
        UITableViewCell *old = [self.tableView cellForRowAtIndexPath:self.lastSelected];
    
        old.accessoryType = UITableViewCellAccessoryNone;
        [old setSelected:FALSE animated:TRUE];
    
    
        // keep track of the last selected cell      
        self.lastSelected = indexPath;
    
    }
    

I built the UITableView via Storyboard.

Was it helpful?

Solution

Just a small adjustment of the logic there:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath*)indexPath
{

    UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];

    if (self.lastSelected && (self.lastSelected.row == indexPath.row)) {
        cell.accessoryType = UITableViewCellAccessoryNone;
        [cell setSelected:NO animated:TRUE];
        self.lastSelected = nil;
    } else {
       cell.accessoryType = UITableViewCellAccessoryCheckmark;
       [cell setSelected:TRUE animated:TRUE];

        UITableViewCell *old = [self.tableView cellForRowAtIndexPath:self.lastSelected];
        old.accessoryType = UITableViewCellAccessoryNone;
        [old setSelected:NO animated:TRUE];
        self.lastSelected = indexPath;
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top