IMTreeView是一个简单的库,允许您使用任何UITableView显示树形结构。它简单、经过充分测试和文档化,完全是Swift编写的。
查看示例项目,看看它是如何工作的!
IMTreeView是用Swift 2编写的,因此需要Xcode 7。
IMTreeView通过CocoaPods提供。要安装它,只需将以下行添加到您的Podfile:
pod "IMTreeView"
要运行示例项目,先克隆仓库,然后在Example目录中运行pod install
。
import IMTreeView
在视图控制器中添加UITableView,无论是通过Storyboard还是通过代码。将tableView的dataSource
设置为UIViewController。
让UIViewController实现UITableViewDataSource
和IMTreeViewDataSource
协议。
按照以下示例实现必要的方法
// MARK: UITableViewDataSource
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1 // or however many you would like to
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// this allows the tableView to function as a tree
return tableView.numberOfItemsInSection(section)
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
// convert the tableView indexPath to a tree-based indexPath
let treeIndexPath = tableView.treeIndexPathFromTablePath(indexPath)
// retrieve the data to display
let node = self.nodeAtIndexPath(treeIndexPath)
// to determine indentation
let level = treeIndexPath.length - 2
// get a cell
let cell = tableView.dequeueReusableCellWithIdentifier("identifier", forIndexPath: indexPath)
// configure cell
cell.textLabel?.text = node.title
cell.indentationLevel = level
return cell
}
// MARK: IMTreeViewDataSource
func tableView(tableView: UITableView, numberOfChildrenForIndexPath indexPath: NSIndexPath) -> Int {
if indexPath.length == 1 {
// return the number of root nodes
return self.nodes.count
} else {
// return the number of children of this node
let node = self.nodeAtIndexPath(indexPath)
return node.children.count
}
}
func tableView(tableView: UITableView, isCellExpandedAtIndexPath indexPath: NSIndexPath) -> Bool {
return true // if supporting collapsing, you should return whether this indexPath is expanded.
}
// MARK: Helpers
func nodeAtIndexPath(indexPath: NSIndexPath) -> Node {
// see example project for implementation
}
Ian McDowell,[email protected]
IMTreeView根据MIT许可提供。有关更多信息,请参阅LICENSE文件。