Search code examples
objective-ciosuitableviewcell

Keep selected cell on heavily reloadRowsAtIndexPaths UITableView


In one of the views there is a UITableView which is getting updated rather often. Tracking the changes are done in a classic way using "reloadRowsAtIndexPaths"

-(void)refreshCells:(NSArray *)changedCells
{
    NSLog(@"refreshCells %i",[changedCells count]);
    [TableView beginUpdates];
    [TableView reloadRowsAtIndexPaths:changedCells withRowAnimation:UITableViewRowAnimationBottom];
    [TableView endUpdates];
}

Question: How can I preserve the user's last selected Cell. the cell position may change after each update refreshCells?


Solution

  • You can save the current selection with

    NSIndexPath *selectedRow = [self.tableView indexPathForSelectedRow];
    

    before the reload and select it again with

    if (selectedRow) {
        [self.tableView selectRowAtIndexPath:selectedRow animated:NO scrollPosition:UITableViewScrollPositionNone];
    }
    

    after the reload. The cell position does not change unless you call insertRowsAtIndexPaths: or deleteRowsAtIndexPaths:.