
NSOutlineView-feature.png
在开发基于osx的Application的过程中,当我们需要显示一组列表结构的数据时,比较容易想到的控件是NSTableView;但如果你显示的数据有层级结构时,NSTableView就会面临一个问题:因为在osx中,NSTableView没有分组功能( sections)
因为在cocoa 中提供了另一个控件供满足我们的需求NSOutlineView它是继承自NSTableView的子类,是Mac OSX Application常用的控件之一,与NSTableView相似,NSOutlineView也使用行和列来显示内容,但所不同的是NSOutlineView使用具有层级的数据结构
下面我们通过一个示例(你也可以从这里Demo下载工程,但更推荐自己一步一步创建工程并实现功能)来简单学习一下怎样使用NSOutlineView显示带有层级结构的数据内容

UI界面
Source List 控件(NSOutlineView)到storyboard中,并添加约束。
初始化设置
Columns = 1 enable Alternating Rows Indentation = 16 
空白效果
这是一个空白的NSOutlineView效果,接下来,我们要添加Data model数据模型,并设置DataSource 和Delegate
NSOutlineView的Data model 与NSTableView有些不同,因为NSOutlineView显示层级结构,因此Data model中要能够表示出这种数据的层级来:root node -> leaf node
RootModel Class

Root Model
在Root Model 中,添加两个属性:name 和isLeaf

name 和isLeaf
Leaf Model Class

LeafModel Class
RootModel 中,添加子节点数组属性

children
模型数据 
setup mode
DataSource 和Delegate 
Data Source 和 Delegate
数据源和代理方法
ViewController 实现方法
numberOfChildrenOfItem->child index: Int ->isItemExpandable cell = outlineView.make(withIdentifier: "HeaderCell", owner: self) as? NSTableCellView
设置根节点cell的重用标识
cell = outlineView.make(withIdentifier: "DataCell", owner: self) as? NSTableCellView
设置子节点cell重用标识

运行效果
展开所有节点或者某一节点

设置展开指定节点
// 展开所有节点
outlineView.expandItem(nil, expandChildren: true)
// 展开第一个节点
// outlineView.expandItem(outlineView.item(atRow: 0), expandChildren: true)
// 展开第二个节点
// outlineView.expandItem(outlineView.item(atRow: 1), expandChildren: true)
展开效果