Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

reloadData in NSTableView but keep current selection

I have anNSTableView showing the contents of a directory. I watch for FSEvents, and each time I get an event I reload my table view. Unfortunately, the current selection then disappears. Is there a way to avoid that?

like image 615
AP. Avatar asked Jun 06 '11 05:06

AP.


2 Answers

Well, you can save selection before calling reloadData and restore it after that.

NSInteger row = [self.tableView selectedRow];
[self.tableView reloadData];
[self.tableView selectRowIndexes:[NSIndexSet indexSetWithIndex:row] byExtendingSelection:NO];

This worked for me in some cases. But if you insert some items BEFORE the selected row, you should andjust your row variable by adding count of added items to it.

like image 182
silvansky Avatar answered Nov 19 '22 00:11

silvansky


Swift 4.2

Create an extension and add a method which preserves selection.

extension NSTableView {

    func reloadDataKeepingSelection() {
        let selectedRowIndexes = self.selectedRowIndexes
        self.reloadData()
        self.selectRowIndexes(selectedRowIndexes, byExtendingSelection: false)
    }
}

Do this in case you use the traditional way of populating table views (not NSArrayController).

like image 12
nsinvocation Avatar answered Nov 19 '22 00:11

nsinvocation