Search code examples
iosuitableviewreloaddata

Reload a table view's data without clearing its selection state


I have a table view with selectable rows. When I reload the table view some new rows might be added (or removed) and some labels in the table view's cells might change. That's what I want to achieve by calling [tableView reloadData].

Unfortunately that method also clears the table view's whole state - including the selection. But I need to keep the selection.

So how can I reload all the data in a table view while still keeping the selected rows selected?


Solution

  • You can store the index path of the selected row with:

    rowToSelect = [yourTableView indexPathForSelectedRow];
    

    Before reload the data. And after reload use:

    [yourTableView selectRowAtIndexPath:rowToSelect animated:YES scrollPosition:UITableViewScrollPositionNone];