Search code examples
iosobjective-cuitableviewcheckmark

Bug when I try to check only one cell in tableview


When I check the first cell after loading – nothing happens, I’m tapping over and over again – nothing happens. I can check other cells, the second, the third etc. and only after that I can check the first cell. This is my method:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    NSUInteger row = indexPath.row;
    NSUInteger oldRow = lastIndexPath.row;
    if (oldRow != row) {
        UITableViewCell *newCell = [tableView cellForRowAtIndexPath:indexPath]; 
        newCell.accessoryType = UITableViewCellAccessoryCheckmark;
        UITableViewCell *oldCell = [tableView cellForRowAtIndexPath:lastIndexPath];
        oldCell.accessoryType = UITableViewCellAccessoryNone;
        lastIndexPath = indexPath;
    }
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

Or maybe you can advise other way to make it (checking only one cell in tableview), because I've found only models with a lot of code and hard to understand.


Solution

  • It is because at first your lastIndexPath variable is nil, so lastIndexPath.row will return 0. If you tap on the first row, that row is also 0, so it won't enter the if statement. Replace that statement with: if (!lastIndexPath || oldRow != row)