How to get selected item of NSOutlineView without using NSTreeController?
Asked Answered
M

3

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.

Mccaffrey answered 12/2, 2010 at 16:42 Comment(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))Bienne
W
80

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

id selectedItem = [outlineView itemAtRow:[outlineView selectedRow]];
Wolfie answered 12/2, 2010 at 17:25 Comment(4)
Thank you SO much that works just as intended. I wish it was easier to find it in the Apple docs...Mccaffrey
Great ! and so simple !Whithersoever
It returns -1 for selected row, can you guide im missing something?Weakminded
@Weakminded that would mean nothing is selected (-1 is NSNotFound).Wolfie
T
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){
            
      }  
   } 
}
Tallie answered 3/8, 2020 at 14:3 Comment(1)
Perfect answer.Ticket
M
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.

Ml answered 6/2, 2017 at 14:57 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.