macosswiftcocoanstableviewnstableviewcell

How to get NSTableView to use a custom cell view mixed with preset cell views?


I have a NSTableView configured in Interface Builder which uses several default cell views. However the first column's cell view needs to be created from a custom class. How do I implement NSTableViewDataSource method tableView.viewForTableColumn() so that it creates the default cell views for the remaining columns?

Here's my method so far:

func tableView(tableView:NSTableView, viewForTableColumn tableColumn:NSTableColumn?, row:Int) -> NSView?
{
    /* Create custom cell view for first column. */
    if (tableColumn?.identifier == "nameColumn")
    {
        let view = tableView.makeViewWithIdentifier("nameCellView", owner: nil) as! NameTableCellView;
        return view;
    }

    /* Return default cell views (defined in IB) for the rest. */
    return tableView.viewAtColumn(??, row: row, makeIfNecessary: true); // How to get column index??
}

How do I get the right column index for tableView.viewAtColumn()? tableView.columnForView() or tableView.columnWithIdentifier() are obviously not any option in this case.


Solution

  • I'd try just giving the default cell your own identifier in Interface Builder...

    enter image description here

    ...then just use that in conjunction with makeViewWithIdentifier::

    func tableView(tableView: NSTableView,
        viewForTableColumn
        tableColumn: NSTableColumn?, row: Int) -> NSView? {
    
            var viewIdentifier = "StandardTableCellView"
    
            if let column = tableColumn {
    
                switch column.identifier {
    
                case "nameColumn":
                    viewIdentifier = "nameCellView"
    
                default: break
    
                }
            }
    
            return tableView.makeViewWithIdentifier(viewIdentifier, owner: self) as? NSView
    }