30

I've got an NSOutlineView bound to an NSTreeController (if that makes a difference), and I'd like to expand every node in my -awakeFromNib().

I'd also like to programatically select the first child of the first node at the same time. These sorts of things are simple with table views, but outlines are not cooperating with me at all.

Thanks,

Rich

Andriy
  • 2,767
  • 2
  • 21
  • 29
Rich Catalano
  • 1,147
  • 1
  • 14
  • 23

2 Answers2

71

I'd like to expand every node in my -awakeFromNib().

As of Mac OS X 10.5, [outlineView expandItem:nil expandChildren:YES].

In previous versions of Mac OS X, you'll need to iterate from 0 to the number of rows, getting the item for each row using [outlineView itemAtRow:row], and storing those items into an array, then iterate the array and pass each item to the expandItem:expandChildren: method. (You can't mix the two loops because expanding an item and all its descendants will change the row indexes of its subsequent siblings; therefore, you must collect all the top-level items first, then expand them once you have all of them.)

I'd also like to programatically select the first child of the first node at the same time.

Immediately after the above, it'll be row 1.

An outline view is a kind of table view, so you'll use one of NSTableView's methods: [outlineView selectRowIndexes:[NSIndexSet indexSetWithIndex:1] byExtendingSelection:NO].

Peter Hosey
  • 95,783
  • 15
  • 211
  • 370
  • Perfect, thanks. Why does passing nil work? I tried that message with just about every object I could think of… – Rich Catalano Feb 06 '09 at 15:27
  • 1
    As the NSOutlineView documentation explains, handing it nil as the item tells it to expand all root items. – Peter Hosey Feb 06 '09 at 16:09
  • 1
    Also related: Don’t drink too much wine when coding and don’t forget to connect the outlet to the NSOutlineView like I did today. ;) – Rafael Bugajewski Jan 25 '12 at 19:59
  • 1
    Apparently adding that call after a reloadData didn't work. Any workarounds? – adib Oct 09 '12 at 14:23
  • 1
    A problem when you want to expand some items in an NSOutlineView programatically at application start is that the NSTreeController prepares it’s content after awakeFromNib is called on your controller. I have found a solution here: http://simplyhacking.com/expanding-nsoutlineview-nodes-at-application-start.html (You have to observe the "content" key-path of your NSTreeController and expand the item as soon as the data has been loaded. Don't forget to remove the observer when you're finished.) – Daniel Feb 15 '13 at 18:32
-1

If you're loading from a datasource,

dispatch_async(dispatch_get_main_queue(), ^{
  [self.outlineView expandItem:root expandChildren:YES];
});
Kyle Browning
  • 5,374
  • 1
  • 19
  • 30