Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

save selected row in UITableView after reloadData

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.

like image 934
vinnitu Avatar asked Dec 01 '09 16:12

vinnitu


4 Answers

The easy way is something like this:

NSIndexPath *ipath = [self.tableView indexPathForSelectedRow];
[self.tableView reloadData];
[self.tableView selectRowAtIndexPath:ipath animated:NO scrollPosition:UITableViewScrollPositionNone];
like image 161
Marco Avatar answered Nov 10 '22 23:11

Marco


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

like image 26
marmor Avatar answered Nov 11 '22 01:11

marmor


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)
    }
}
like image 12
muhasturk Avatar answered Nov 10 '22 23:11

muhasturk


The workaround is to use reloadSections: instead of reloadData. For some reason reloadData removes the current selection.

like image 5
Greg Avatar answered Nov 11 '22 00:11

Greg