I write custom jabber client in iphone.
I use xmppframework as engine.
And I have UITableViewController with NSMutableArray for repesent contact list.
When i receive(or somebody change it contents) roster (aka contact list) i wanna change UITableView items (add/remove/modify). So if User work with listView at time when list updates by
[items addObject:newItem];
[self.tableView reloadData];
user lost current selection item.
So, my question is howto save (if possible, i mean if given selected item not removed) current select item after reloadData?
Thx.
The easy way is something like this:
NSIndexPath *ipath = [self.tableView indexPathForSelectedRow];
[self.tableView reloadData];
[self.tableView selectRowAtIndexPath:ipath animated:NO scrollPosition:UITableViewScrollPositionNone];
Adding a bit to Marco's answer:
First, if you're using multiple selection, you can add this method to your ViewController
and call it whenever you need to call [tableView reloadData]
:
- (void)reloadTableView
{
NSArray *indexPaths = [self.tableView indexPathsForSelectedRows];
[self.tableView reloadData];
for (NSIndexPath *path in indexPaths) {
[self.tableView selectRowAtIndexPath:path animated:NO scrollPosition:UITableViewScrollPositionNone];
}
}
Second, if you're in a UITableViewController
and you want to preserve selection after tableView appears there's a feature in UITableViewController: clearsSelectionOnViewWillAppear
you can turn on or off.
See here: http://developer.apple.com/library/ios/#documentation/uikit/reference/UITableViewController_Class/Reference/Reference.html
Swift 4.2 Tested
The correct way to update selected rows after reload table view is:
let selectedRows = tableView.indexPathsForSelectedRows
tableView.reloadData()
DispatchQueue.main.async {
selectedRows?.forEach { selectedRow in
tableView.selectRow(at: selectedRow, animated: false, scrollPosition: .none)
}
}
The workaround is to use reloadSections: instead of reloadData. For some reason reloadData removes the current selection.
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