如何在不使用NSTreeController的情况下获取NSOutlineView的所选项目?

30

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

我希望有像以下这样的东西:

array = [outlineViewOutlet selectedItems];

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


1
如果有人偶然发现这个问题并尝试寻找Swift的答案,这是以下代码的移植:println(MainOutlineList.itemAtRow(MainOutlineList.selectedRow)) - nsij22
3个回答

80

NSOutlineView 继承自 NSTableView,因此您可以使用像 selectedRow 这样的好方法:

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

1
非常感谢,它完全按照预期工作。但愿在苹果文档中更容易找到它... - Ronaldo Nascimento
太棒了!而且非常简单! - Colas
它返回所选行的-1,你能指导一下我错过了什么吗? - Xander
@Xander 这意味着没有选择任何东西(-1NSNotFound)。 - Dave DeLong

4

Swift 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) {
      
    }
}

小贴士:您也可以通过以下方式获取所选项的父项

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){
            
      }  
   } 
}

1
完美的答案。 - Lakshmi Yadav

1

@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)")
    }
}

展示的是一个来自FileSystemItem类的项目,它具有fileURL属性。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接