0

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.

2 Answers2

2

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)

Levi
  • 7,313
  • 2
  • 32
  • 44
  • Can you help me again? Checking only one cell works, but now I need opportunity to uncheck cell and leave the whole tableview unchecked. I thought that `else if (cell.accessoryType == UITableViewCellAccessoryCheckmark) { cell.accessoryType = UITableViewCellAccessoryNone; }` will work but it doesn't. – Alexander Yakovlev Nov 18 '13 at 22:36
  • Post the entire method – Levi Nov 19 '13 at 09:07
  • I've found the solution `BOOL isSelected = (cell.accessoryType == UITableViewCellAccessoryNone); ……………… else if (oldRow == row) { cell.accessoryType = isSelected ? UITableViewCellAccessoryCheckmark : UITableViewCellAccessoryNone; }` But when I save `cell.textlabel.text` in plist, save the "state" of cell (its checkmark) and then I load it into my tableview – the selection don't work properly. So maybe I should post it into next question. Thanks for help! – Alexander Yakovlev Nov 20 '13 at 20:42
0
- (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];
}
Cy-4AH
  • 4,370
  • 2
  • 15
  • 22