始终对 NSTableView 进行排序

Always sort NSTableView

如何始终对 NSTableView 中的列进行排序? 当我的视图加载时,数据未排序,数据更新时也是如此。现在只有当我点击 header 列时,数据才会排序。

这是我在单击 header 列时对数据进行排序的代码:

在 ViewDidLoad 中:

let descriptorName = NSSortDescriptor(key: "designation", ascending: true, selector: #selector(NSString.caseInsensitiveCompare(_:)))
tableview.tableColumns[0].sortDescriptorPrototype = descriptorName

委托函数:

func tableView(_ tableView: NSTableView, sortDescriptorsDidChange oldDescriptors: [NSSortDescriptor]) {
    let dataArrayMutable = NSMutableArray(array: self.data)
    dataArrayMutable.sort(using: tableView.sortDescriptors)
    self.data = (dataArrayMutable as NSArray) as! [Article]
    tableview.reloadData()
}

问题已解决: 我必须在加载 tableView 之前对数据数组中的数据进行排序。这是代码:

data = data.sorted(by: { [=12=].designation! < .designation! })

数据源中元素的顺序决定了 table 视图中元素的顺序。这就是为什么当您的数据源(技术上不是您的代表)被告知排序描述符已更改时,您所做的就是更改数据源管理的数据的顺序。

因此,您的问题的答案只是让数据源的数据从一开始就保持所需的顺序。不要只在 tableView(_:sortDescriptorsDidChange:) 中排序。从头开始排序。

当然,如果动态添加数据,需要维护排序顺序。您可以使用 index(of:inSortedRange:options:usingComparator:) 查找插入新元素的位置以保持排序顺序。或者,您可以在任意位置添加数据,然后重新排序。