我想实现一个outlineView,它将字符串值显示为根值。以下代码适用于我:
import Cocoa
class TestController: NSViewController, NSOutlineViewDataSource, NSOutlineViewDelegate {
@IBOutlet weak var outlineView: NSOutlineView!
var items: [String] = ["Item 1", "Item 2", "Item 3", "Item 4","Item 5"]
func outlineView(_ outlineView: NSOutlineView, child index: Int, ofItem item: Any?) -> Any {
return items[index]
}
func outlineView(_ outlineView: NSOutlineView, isItemExpandable item: Any) -> Bool {
return true
}
func outlineView(_ outlineView: NSOutlineView, numberOfChildrenOfItem item: Any?) -> Int {
if item == nil {
return items.count
}
return 0
}
func outlineView(_ outlineView: NSOutlineView, viewFor tableColumn: NSTableColumn?, item: Any) -> NSView? {
let v = outlineView.make(withIdentifier: "HeaderCell", owner: self) as! NSTableCellView
if let tf = v.textField {
tf.stringValue = item as! String
}
return v
}
}
结果如下:
但我不知道,我如何为第1项分配不同的字符串值(例如)。我希望能够实现这样的目标:
+Item 1
++Sub Item 1.1
++Sub Item 1.2
+Item 2
++Sub Item 2.1
+Item 3
++Sub Item 3.1
++Sub Item 3.2
++Sub Item 3.3
...
有人能帮助我吗?
答案 0 :(得分:0)
如果要显示分层数据,则数据不能是简单的字符串数组。而不是项目字符串,使用具有标题/名称和子属性的字典或自定义对象。 children属性是一系列子项。
func outlineView(_ outlineView: NSOutlineView, child index: Int, ofItem item: Any?) -> Any
会返回item
的子项。如果item
是"项目1"并且index
为1,返回值为"子项1.2"。
func outlineView(_ outlineView: NSOutlineView, numberOfChildrenOfItem item: Any?) -> Int
返回``的子项数。如果item
是"项目1" ,返回值为2。