Search code examples
iosxcodeios4ios5xcode4

UITableView Checkmark ONLY ONE Row at a Time


With this code, I can check multiple rows in a table.

But what I want is to only have one row checked at a time. Here's my code:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    UITableViewCell *theCell = [tableView cellForRowAtIndexPath:indexPath];
    
    if (theCell.accessoryType == UITableViewCellAccessoryNone) {
        theCell.accessoryType = UITableViewCellAccessoryCheckmark;
    } else if (theCell.accessoryType == UITableViewCellAccessoryCheckmark) {
        theCell.accessoryType = UITableViewCellAccessoryNone;
    }
}

If a user selects a different row, then I want the old row to simply automatically uncheck. Don't know how to do that.


Solution

  • The best way is to set the accessory type in cellForRowAtIndexPath.

    Use didSelectRowAtIndexPath to only record which path should be selected and then call reloadData.