Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 960
Mischa Avatar asked Oct 21 '13 23:10

Mischa


People also ask

How to reload UITableView?

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.

How do I know if Iitableview has completed reloadData?

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.

How tableView works?

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.


2 Answers

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];
like image 114
JeroValli Avatar answered Sep 19 '22 18:09

JeroValli


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];
}
like image 32
Mischa Avatar answered Sep 18 '22 18:09

Mischa