我构建了一个 NSOutlineView
,它从 NSTreeController
获取动态更新的数据,并且一切正常。我似乎无法做的是根据 NSOutlineView 中的用户选择从那里向后工作。
var deviceStore = [TreeNode]()
是我的实时更新的后备数据存储它是一个 Device
对象数组,它可能(或可能不)包含一个 Service
对象数组作为 children 。
这一切都有效。但是,当我在 Outline View 中选择一行时,我需要按照自己的方式返回到 deviceStore 中的原始对象——或者,至少,从 OutlineView 中获取显示的数据,以便我可以走遍 deviceStore 以找到原始项目。
我得到的是 func outlineViewSelectionDidChange(_ notification: Notification) {}
,它在进行选择时调用,我可以从中通过 提取 NSTreeController TreeNode treeController.selectedNodes
但从那里开始,我陷入了困境。 selectedNodes 是所选节点的完整数组,因此如果它是子(叶)节点,则它包括其父节点及其所有兄弟节点。
selectedNodes
数组如下所示:
<NSTreeControllerTreeNode: 0x6080000c4590>, child nodes {
0:<NSTreeControllerTreeNode: 0x6000000ca6b0>, child nodes {
0:<NSTreeControllerTreeNode: 0x6000000caf70>, child nodes {}
1:<NSTreeControllerTreeNode: 0x6000000cafe0>, child nodes {}
2:<NSTreeControllerTreeNode: 0x6000000cb050>, child nodes {}
}
1:<NSTreeControllerTreeNode: 0x6080000d1790>, child nodes {
0:<NSTreeControllerTreeNode: 0x6000000cce80>, child nodes {}
}
}
并且selectedIndex为4。
我看不出如何从这些信息中返回到我的数据模型中的 deviceStore[0].serviceStore[2]。
如果我可以从所选行检索服务 ID 列中的值,我可以简单地遍历 deviceStore 树来找到它。
我确信有一种简单、优雅、简单的方法可以做到这一点,我只是还没有找到,但是对于NSTreeController
s 和NSOutlineView
s 是新手我迷路了。
最佳答案
您可以尝试像这样直接访问关联的对象:
let selectedService = treeController.selectedObjects.first as? Service
文档 are here .
还要确保您的 NSTreeController
已正确配置为使用您的类的对象:
或者(如果您想直接使用您的数据源)您可能需要 get the index path NSTreeController
中的选定对象:
var selectionIndexPath: IndexPath? { get }
关于swift - 在 NSOutlineView 选择上获取 NSTreeController 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41509387/