reloadData in NSTableView but keep current selection

后端 未结 3 919
时光说笑
时光说笑 2021-02-12 17:20

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 sele

相关标签:
3条回答
  • 2021-02-12 17:51

    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).

    0 讨论(0)
  • 2021-02-12 17:59

    It depends on how you populate your NSTableView.

    If you have the table view bound to an NSArrayController, which in turn contain the items that your table view is displaying, then the NSArrayController has an option to preserve the selection. You can select it (or not) from within Interface Builder as a property on the NSArrayController. Or you can use the setPreservesSelection method in code.

    However, if you completely replace the array of items that the NSArrayController manages each time you get your FSEvents, then maybe the preservation of selection cannot work. Unfortunately the Apple docs on this property of NSArrayController are a bit vague as to when it can and cannot preserve the selection.

    If you are not using an NSArrayController, but maybe using a dataSource to populate the table view, then I think you'll have to manage the selection yourself.

    0 讨论(0)
  • 2021-02-12 18:01

    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.

    0 讨论(0)
提交回复
热议问题