【问题标题】:How to get selected item of NSOutlineView without using NSTreeController?如何在不使用 NSTreeController 的情况下获取 NSOutlineView 的选定项?
【发布时间】:2011-01-16 05:48:21
【问题描述】:

如何使用我自己的数据源获取 NSOutlineView 的选定项。 我看到我可以获得 selectedRow 但它返回相对于大纲状态的行 ID。这样做的唯一方法是跟踪项目的展开折叠状态,但这似乎很荒谬。

我希望得到类似的东西:

array = [outlineViewOutlet selectedItems];

我看了其他类似的问题,他们似乎没有回答这个问题。

【问题讨论】:

  • 如果有人偶然发现这个并试图为 swift 找到答案,这是下面代码的一个端口。 println(MainOutlineList.itemAtRow(MainOutlineList.selectedRow))

标签: cocoa pyobjc


【解决方案1】:

NSOutlineView 继承自 NSTableView,所以你会得到像 selectedRow 这样的好方法:

id selectedItem = [outlineView itemAtRow:[outlineView selectedRow]];

【讨论】:

  • 非常感谢您按预期工作。我希望在 Apple 文档中更容易找到它...
  • 太棒了!如此简单!
  • 它为选定的行返回-1,你能指导我错过了什么吗?
  • @Xander 这意味着没有选择任何内容(-1NSNotFound)。
【解决方案2】:

斯威夫特 5

NSOutlineView 有一个委托方法outlineViewSelectionDidChange

 func outlineViewSelectionDidChange(_ notification: Notification) {

    // Get the outline view from notification object
    guard let outlineView = notification.object as? NSOutlineView else {return}

    // Here you can get your selected item using selectedRow
    if let item = outlineView.item(atRow: outlineView.selectedRow) {
      
    }
}

额外提示:您还可以像这样获取所选项目的parent item

func outlineViewSelectionDidChange(_ notification: Notification) {

// Get the outline view from notification object
guard let outlineView = notification.object as? NSOutlineView else {return}

// Here you can get your selected item using selectedRow
if let item = outlineView.item(atRow: outlineView.selectedRow) {
  
     // Get the parent item
      if let parentItem = outlineView.parent(forItem: item){
            
      }  
   } 
}

【讨论】:

  • 完美答案。
【解决方案3】:

@Dave De Long:很好的答案,这里是 Swift 3.0 的翻译

@objc private func onItemClicked() {
    if let item = outlineView.item(atRow: outlineView.clickedRow) as? FileSystemItem {
        print("selected item url: \(item.fileURL)")
    }
}

显示的是项目来自具有属性 fileURL 的类 FileSystemItem 的情况。

【讨论】:

    猜你喜欢
    • 2010-11-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多