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

2.1k views Asked by At

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.

2

There are 2 answers

1
Paul Patterson On BEST ANSWER

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
}
0
Alfonso Tesauro On

I came across a good solution to the problem: You could make the table column identifiers to be the same of the corresponding view cells identifiers. After that, you could use in your delegate:

- (NSView *)tableView:(NSTableView *)tableView
   viewForTableColumn:(NSTableColumn *)tableColumn
                  row:(NSInteger)row {

    NSTableCellView *cell = [tableView makeViewWithIdentifier:[tableColumn identifier] owner:NULL];


    return cell;
}

From this starting point, you can easily take action for a specific column identifier and make another cellview instead according to your logic.