Show list of strings in Source List (NSOutlineView

2019-06-11 08:28发布

问题:

I'm trying to show a simple list of strings in a source list sidebar - similar to that in Finder or the Github app. From reading the protocol reference I can't see which method is setting what the view displays. So far I have:

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
}

And all I get is a source list with four blank items (No text). Do I need to override another method from the NSOutlineViewDelegate to show the information?

回答1:

If you're happy to use a view-based outline view, rather than a cell-based one, you can replace the delegate method outlineView:dataCellForTableColumn:item, with its view equivalent 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
} 

Note that the important call within this method is the NSTableView method makeViewWithIdentifier:owner:. The first argument to this method - the string DataCell - is the value of the identifier Interface Builder gives to the NSTableViewCell object that it automatically inserts into your NSOutlineView when you drag it onto the canvas. This object has a textField property, and an imageView; all you need to do is set the stringValue property of the textField to the value of item.