30

How do I get the selected item of an NSOutlineView with using my own data source. I see I can get selectedRow but it returns a row ID relative to the state of the outline. The only way to do it is to track the expanded collapsed state of the items, but that seems ridiculous.

I was hoping for something like:

array = [outlineViewOutlet selectedItems];

I looked at the other similar questions, they dont seem to answer the question.

Ronaldo Nascimento
  • 1,571
  • 3
  • 21
  • 40
  • 1
    In case anyone stumbles on this and is trying to find an answer for swift, this is a port of the below code. `println(MainOutlineList.itemAtRow(MainOutlineList.selectedRow))` – nsij22 Apr 28 '15 at 20:30

3 Answers3

80

NSOutlineView inherits from NSTableView, so you get nice methods such as selectedRow:

id selectedItem = [outlineView itemAtRow:[outlineView selectedRow]];
Dave DeLong
  • 242,470
  • 58
  • 448
  • 498
4

Swift 5

NSOutlineView has a delegate method 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) {
      
    }
}

Bonus Tip: You can also get the parent item of the selected item like this:

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){
            
      }  
   } 
}
M Afham
  • 834
  • 10
  • 15
1

@Dave De Long: excellent answer, here is the translation to Swift 3.0

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

Shown is a case where item is from class FileSystemItem with a property fileURL.

pkamb
  • 33,281
  • 23
  • 160
  • 191
Erich Kuester
  • 460
  • 4
  • 11