Search code examples
iosobjective-cuitableviewtogglecheckmark

Toggle checkmark between cells with one cell checked by default


I have a settings view in my app that I want the user to be able to check between some different settings but only let the user to have one of the options selected at the time.

I got some help throughout this answer: iPhone :UITableView CellAccessory Checkmark

But I'm not able to get it to toggle correctly when I have the first cell checked by default.

This is in my cellForRowAtIndexPath

if (indexPath.row == 0)
{
     // Set the first cell checked by default
     cell.accessoryType = UITableViewCellAccessoryCheckmark;
}
else if([self.checkedIndexPath isEqual:indexPath])
{
     cell.accessoryType = UITableViewCellAccessoryCheckmark;
}
else
{
     cell.accessoryType = UITableViewCellAccessoryNone;
}

This is my didSelectRowAtIndexPath

// Uncheck the previous checked row
if(self.checkedIndexPath)
{
    UITableViewCell* uncheckCell = [tableView cellForRowAtIndexPath:self.checkedIndexPath];
    uncheckCell.accessoryType = UITableViewCellAccessoryNone;
}

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

 [tableView deselectRowAtIndexPath:indexPath animated:YES];

The cell is checked by default but when checking another cell the first cell is still checked until I check it again and after that check another cell, then the behavior is correct.


Solution

  • if (!self.checkedIndexPath && indexPath.row == 0)
    {
         // save away what cell is already checked
         self.checkedIndexPath = indexPath;
    
         // Set the first cell checked by default
         cell.accessoryType = UITableViewCellAccessoryCheckmark;
    }
    ...
    

    alternatively: if(!self.checkedIndexPath) self.checkedIndexPath = indexPath;

    if([self.checkedIndexPath isEqual:indexPath])
    {
        ...
    }
    else
    {
        ...
    }
    

    alternate in your viewDidLoad add self.checkedIndexPath = [NSIndexPath indexPath forRow:0 inSection:0];

    and then just have the checkedIndexPath = indexPath check in your cellFor...