Search code examples
swiftnstableviewnsmenu

Display menu on NSTableView if a row is selected


I have a menu on the outlet of an NSTableView. It will show the menu when I right click on the Table View, but I don't want to show the menu if there is no row selected. How can I stop the menu from showing when I right click and there is no row selected?

I have tried the:

validateMenuItem 

but it never gets called

I have tried NSMenuDelegate and its

func menuWillOpen(_ menu: NSMenu) { }

and

func menuNeedsUpdate(_ menu: NSMenu) { }

but none of them return anything that I can set to DONT show menu IF...

The suggested duplicate asks to prevent displaying the contextual menu when clicking on a specific cell. This question is about preventing the menu to show when no ROW is selected.


Solution

  • It was pretty easy:

    Implement

    NSMenuDelegate

    and add this method:

    func menuWillOpen(_ menu: NSMenu) {
            if myTableView.selectedRow < 0 {
                menu.cancelTrackingWithoutAnimation()
            }
        }