swift - 在 NSOutlineView 选择上获取 NSTreeController 数据

标签 swift macos nsoutlineview nstreecontroller

我构建了一个 NSOutlineView,它从 NSTreeController 获取动态更新的数据,并且一切正常。我似乎无法做的是根据 NSOutlineView 中的用户选择从那里向后工作。

    var deviceStore = [TreeNode]()

是我的实时更新的后备数据存储它是一个 Device 对象数组,它可能(或可能不)包含一个 Service 对象数组作为 children 。

这一切都有效。但是,当我在 Outline View 中选择一行时,我需要按照自己的方式返回到 deviceStore 中的原始对象——或者,至少,从 OutlineView 中获取显示的数据,以便我可以走遍 deviceStore 以找到原始项目。

我得到的是 func outlineViewSelectionDidChange(_ notification: Notification) {},它在进行选择时调用,我可以从中通过 提取 NSTreeController TreeNode treeController.selectedNodes 但从那里开始,我陷入了困境。 selectedNodes 是所选节点的完整数组,因此如果它是子(叶)节点,则它包括其父节点及其所有兄弟节点。

然后给出此处显示的表格: OutlineView

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 树来找到它。

我确信有一种简单、优雅、简单的方法可以做到这一点,我只是还没有找到,但是对于NSTreeControllers 和NSOutlineViews 是新手我迷路了。

最佳答案

您可以尝试像这样直接访问关联的对象:

let selectedService = treeController.selectedObjects.first as? Service

文档 are here .

还要确保您的 NSTreeController 已正确配置为使用您的类的对象:

enter image description here

或者(如果您想直接使用您的数据源)您可能需要 get the index path NSTreeController 中的选定对象:

var selectionIndexPath: IndexPath? { get }

关于swift - 在 NSOutlineView 选择上获取 NSTreeController 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41509387/

相关文章:

ios - 如何使用 ObjectMapper 映射带有动态键的字典?

ios - 如何在 Swift 中使用查询语句检索数据?

ios - swift:导航栏模糊效果

delphi - 哪个版本的 Delphi 可以让我创建在 Mac 上运行的软件?

c++ - 如何获得正在监听的端口列表及其各自的应用程序名称

objective-c - cocoa 文本菜单和修改 NSOutlineView 中的字体

objective-c - 如何禁用 NSOutlineView 中元素的所有子树展开?

swift - 如何创建具有不同 'Product Module Name' 和 'Product Name' 的项目并将其模块导入另一个项目?

xcode - 在 Xcode 4.0 中自动构建 DMG

objective-c - EXC_BAD_ACCESS 在启用 ARC 的情况下实现 NSOutlineViewDataSource