【问题标题】:How to sort NSTableView with NSArrayController programmatically?如何以编程方式使用 NSArrayController 对 NSTableView 进行排序?
【发布时间】:2018-01-27 01:31:18
【问题描述】:

我有一个只有一列但子视图中的值不同的 NSTableView。 tableView 由绑定到 CoreData 实体的 NSArrayController 填充。 我想知道如何通过自定义按钮对 tableView 进行排序。

class ViewController: NSViewController {

   @IBOutlet var arrayController: NSArrayController!

   @IBAction func sortByName(_ sender: Any) {

       arrayController.sort... ?
   }

   @IBAction func sortByAge(_ sender: Any) {

       arrayController.sort... ?

   }

}

我知道如何通过单击行标题使 NSArrayController 对列进行排序。但由于我只有一列但值不同,我试图找到一种按自定义按钮排序的方法。 任何帮助将非常感激。

【问题讨论】:

  • 您是否尝试过更改排序描述符?

标签: swift macos core-data tableview nsarraycontroller


【解决方案1】:

设置数组控制器的sortDescriptors属性并调用arrayController.rearrangeObjects()

class ViewController: NSViewController {

    @IBOutlet var arrayController: NSArrayController!

    @IBAction func sortByName(_ sender: Any) {
        sortArrayController(by: "name")
    }

    @IBAction func sortByAge(_ sender: Any) {
        sortArrayController(by: "age")
    }

    func sortArrayController(by key : String) {
        arrayController.sortDescriptors = [NSSortDescriptor(key: key, ascending: true)]
        arrayController.rearrangeObjects()
    }

}

【讨论】:

  • 正是我想要的。非常感谢!
  • 您不必调用rearrangeObjects,设置sortDescriptors 即可。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-07-25
  • 1970-01-01
  • 2021-10-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多