简体   繁体   中英

Programmatically sorting NSTableView

I know how to make a tableview user-click sortable but how to sort it programmatically (without using an NSArrayController)? The docs are skimpy on this. Here is what I got:

private func updateThemeTableView()
{
    _tableViewDataDict = getAssociatedThemesFor(_type);
    _tableView.reloadData();

    let sort = NSSortDescriptor(key: "Theme", ascending: true, selector: "caseInsensitiveCompare:");
    _tableView.sortDescriptors = [sort];
}

But this doesn't work.

What is the key used here? Should this be the table view column name or the column identifier (set in IB)?

When to apply the sort? (I suppose after _tableViewDataDict received the data and reloadData(), whereafter NSTableViewDataSource.viewForTableColumn() does its business?)

Is the sort selector valid or do I have to provide a method for this?

Setting the table's sort descriptors is not enough. You also need to respond to the NSTableViewDelegate method optional func tableView(_ aTableView: NSTableView, sortDescriptorsDidChange oldDescriptors: [AnyObject]) by applying the sort descriptors to your data model then reloading the table's data (via reloadData() ). This is true whether you're applying sort descriptors to the entire table (which doesn't let users click column headers) or to individual columns (which does let users click column headers).

As mentioned in comments, you can't sort a dictionary, so you'll need to cache a sorted array and let the table data source methods reference the array instead of the dictionary.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM