Implementing context menu for NSTableCellView

117 Views Asked by At

I have a table view where I would like to have a different context menu appear when right-clicking on a cell vs. when right-clicking on an area where there are no cells. I'm trying to do this using storyboards in the interface builder.

If I attach a menu to the NSTableView I can get a context menu to appear. However, if I attach a menu to the NSTableCellView I get the NSTableView's context menu rather than the menu I have attached to the NSTableCellView.

I know I could do all this via code by having one menu attached the the NSTableView and change it's contents based on the cell clicked but I believe I should be able to do this by attaching different menus to different views in the view heirachy.

Can this be done solely in interface builder?

1

There are 1 best solutions below

0
act1292 On

As per Willeke's suggestion I sub-classed the NSTableView and added the the following code to the menu property:

- (NSMenu*) menu
{
    if (self.clickedRow == -1 || self.clickedColumn == -1) return super.menu;

    NSTableCellView *clickedCell = [self viewAtColumn:self.clickedColumn row:self.clickedRow makeIfNecessary:FALSE];
    
    if (clickedCell != nil) return clickedCell.menu;

    return self.menu;
}

With this implementation I get the behavior I was looking for.