在Swift中显示源列表(NSOutlineView)中的字符串列表

时间:2015-01-25 06:58:34

标签: macos cocoa swift nsoutlineview

我正在尝试在源列表侧边栏中显示一个简单的字符串列表 - 类似于Finder或Github应用程序中的字符串。从阅读protocol reference我无法看到哪种方法设置了视图显示的内容。到目前为止,我有:

var items: [String] = ["Item 1", "Item 2", "Item is an item", "Thing"]
func outlineView(outlineView: NSOutlineView, child index: Int, ofItem item: AnyObject?) -> AnyObject {
    return items[index]
}

func outlineView(outlineView: NSOutlineView, isItemExpandable item: AnyObject) -> Bool {
    return false
}
func outlineView(outlineView: NSOutlineView, numberOfChildrenOfItem item: AnyObject?) -> Int {
    if item == nil {
        return items.count
    }
    return 0
}
func outlineView(outlineView: NSOutlineView, objectValueForTableColumn tableColumn: NSTableColumn?, byItem item: AnyObject?) -> AnyObject? {
    return "ITEM"
}
func outlineView(outlineView: NSOutlineView, setObjectValue object: AnyObject?, forTableColumn tableColumn: NSTableColumn?, byItem item: AnyObject?) {
    println(object, tableColumn, item)
}
// Delegate
func outlineView(outlineView: NSOutlineView, dataCellForTableColumn tableColumn: NSTableColumn?, tem item: AnyObject) -> NSCell? {
    println("Called")
    let view = NSCell()
    view.stringValue = item as String
    return view
}

我得到的是一个包含四个空白项目的源列表(无文本)。我是否需要覆盖NSOutlineViewDelegate中的另一个方法来显示信息?

1 个答案:

答案 0 :(得分:3)

如果您乐意使用基于视图的大纲视图,而不是基于单元格的大纲视图,则可以替换委托方法{{1其视图等效outlineView:dataCellForTableColumn:item

outlineView:viewForTableColumn:item:

请注意,此方法中的重要调用是func outlineView(outlineView: NSOutlineView, viewForTableColumn tableColumn: NSTableColumn?, item: AnyObject) -> NSView? { var v = outlineView.makeViewWithIdentifier("DataCell", owner: self) as NSTableCellView if let tf = v.textField { tf.stringValue = item as String } return v } 方法NSTableView。此方法的第一个参数 - 字符串 DataCell - 是makeViewWithIdentifier:owner: Interface Builder 赋予identifier对象的值,它自动插入将其拖动到画布上时,将NSTableViewCell放入其中。该对象具有NSOutlineView属性和textField;您需要做的就是将imageView的{​​{1}}属性设置为stringValue的值。