简体   繁体   中英

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.

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

在此处输入图片说明

...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
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM