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?
If you want to reload your table view while also saving and restoring any selections, you should take a copy of the indexPathsForSelectedRows property before the reload, then re-apply those selections after calling reloadData() . With that in place, you can now call yourTableView.
When [tableView reloadData] returns, the internal data structures behind the tableView have been updated. Therefore, when the method completes you can safely scroll to the bottom. I verified this in my own app.
A table view displays a single column of vertically scrolling content, divided into rows and sections. Each row of a table displays a single piece of information related to your app. Sections let you group related rows together. For example, the Contacts app uses a table to display the names of the user's contacts.
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];
JeroVallis solution works for single selection table views. Based on his idea this is how I made it work with multiple selection:
NSArray *selectedIndexPaths = [self.tableView indexPathsForSelectedRows];
[tableView reloadData];
for (int i = 0; i < [selectedIndexPaths count]; i++) {
[tableView selectRowAtIndexPath:selectedIndexPaths[i] animated:NO scrollPosition:UITableViewScrollPositionNone];
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With