View accessories in UITableView: view is not updated

I am trying to add checkmarks to elements when the user selects rows as a table. However, the view is not updated, and the checkmarks are not displayed:

- (void)tableView:(UITableView *)tv didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

    UITableViewCell* oldCell = [self tableView:tv cellForRowAtIndexPath:[NSIndexPath indexPathForRow:selectedIndex inSection:0]];
    oldCell.accessoryType = UITableViewCellAccessoryNone;

    if (indexPath.section == 0) {
        selectedIndex = indexPath.row;
    }

    UITableViewCell* newCell = [self tableView:tv cellForRowAtIndexPath:indexPath];
    newCell.accessoryType = UITableViewCellAccessoryCheckmark;

    [tv deselectRowAtIndexPath:indexPath animated:NO];
}

What could be the reason for this?

+3
source share
1 answer

Call cellForRowAtIndexPath directly on the tv object, not through self, to make sure you return the correct cell reference:

- (void)tableView:(UITableView *)tv didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

    UITableViewCell *oldCell = [tv cellForRowAtIndexPath:[NSIndexPath indexPathForRow:selectedIndex inSection:0]];
    oldCell.accessoryType = UITableViewCellAccessoryNone;

    if (indexPath.section == 0) {
        selectedIndex = indexPath.row;
    }

    UITableViewCell *newCell = [tv cellForRowAtIndexPath:indexPath];
    newCell.accessoryType = UITableViewCellAccessoryCheckmark;

    [tv deselectRowAtIndexPath:indexPath animated:NO];
}

Also make sure that you have this logic in cellForRowAtIndexPath:

...
if (indexPath.row == selectedIndex)
    cell.accessoryType = UITableViewCellAccessoryCheckmark;
else
    cell.accessoryType = UITableViewCellAccessoryNone;
...
return cell;

otherwise, the checkmark will remain in the cell after scrolling the screen and return to the screen even after you select another cell.

+6
source

Source: https://habr.com/ru/post/1746647/


All Articles