Alexander Yakovlev
Alexander Yakovlev

Reputation: 510

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.

Upvotes: 0

Views: 163

Answers (2)

Cy-4AH
Cy-4AH

Reputation: 4585

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell* cell;
    //cell creation code
    cell.accessoryType = nil != lastIndexPath && lastIndexPath.row == indexPath.row ? UITableViewCellAccessoryCheckmark : UITableViewCellAccessoryNone;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSArray* reloadRows = nil == lastIndexPath ? @[indexPath] : @[lastIndexPath, indexPath];
    lastIndexPath = indexPath;
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    [tableView reloadRowsAtIndexPaths:reloadRows withRowAnimation: UITableViewRowAnimationAutomatic];
}

Upvotes: 0

Levi
Levi

Reputation: 7343

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)

Upvotes: 2

Related Questions