Use NSOutlineView With NSTreeController

This article describes the steps to use NSOutlineView With NSTreeController. The source code can be downloaded here.

Development environment:

  • OS X: 10.11.4
  • XCode: 7.3
  • Swift: 2.2

Steps

Create Basic Project

Refer to commit till #40ccec2.

Add UI Controls

Refer to commit till #2853186.
After done, the UI looks like:

Add Model Class of “Node”

Refer to commit till #516acc4.

1
2
3
4
5
6
7
8
9
10
11
12
class Node: NSObject {
var title = "Node"
var children = [Node]()
override init() {
super.init()
}
init(title: String) {
self.title = title
}
}

Prepare Demo Nodes Data

Refer to commit till #f914811.
Node structure:
- Node
- Group
-– Node A
-– Node B

Add and Configure NSTreeController

Refer to commit till #06b01a8.
Steps

  • Add NSTreeController in the .xib and select it.
  • Go to “Attricutes Inspector”.
    • Set the “Key Paths > Children” to “children”.
    • Choose “Mode” Class and set “Class Name” to “OutlineWithController.Node”.
    • Select “Prepares Content”

  • Go to “Binding Inspector”.
    • Bind “Content Array” to self.nodes (which was created in previous step, and it should be dynamic).

Bind NSOutlineView

Refer to commit till #f941f7b.
Steps

  • Select “Outline View”.
  • Go to “Binding Inspector”.
    • Bind “Content” to “Tree Controller”‘s “arrangedObjects”. Ignore the warning in “Model Key Path”.
    • Bind “Selection Index Paths” to Tree Controller’s “selectionIndexPaths”.

  • Select “Table View Cell”.
  • Go to “Binding Inspector”.
    • Bind “Content” to “Tree Cell View”‘s “objectValue.title”. Node: here the “objectValue” is the class Node as you defined it in the tree controller.

  • Go to “Attributes Inspector”.
    • Set “Behavior” to “Editable”.

Run the app, you should see the app like:

Add Node and Remove It

Refer to commit till #d9b7197.
Steps

  • Right click on the tree controller.
  • Connect “add:” to “Add Node” menu item.
  • Connect “addChild:” to “Add Child Node” menu item.
  • Connect “remove:” to edit button.

That’s it. Run the app. You should be able to add node or remove it.

Edit Selected Node

Refer to commit till #22e2c07.
The key code is here:

1
2
3
4
5
6
@IBAction func editNode(sender: NSObject) {
let row = outlineView.selectedRow
if row != -1 {
outlineView.editColumn(0, row: row, withEvent: nil, select: true)
}
}

Disable Remove and Edit Controls if no Node Selected

Refer to commit till #eb7decd.
The key point is to bind the “Enabled” attribute to tree controller’s “canRemove” controller key.
Another point is, when app starts maybe nothing was selected. In this case, disable the Outline’s “Attributes > Selection > Empty”, and select the Tree Controller’s “Attributes > Avoid Empty Selection”.