-1

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.

Ryuuzaki Julio
  • 369
  • 1
  • 14
  • 1
    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. – Ryuuzaki Julio Apr 06 '18 at 11:34
  • The solution is the same. Instead of `row == self.numberOfRows - 1` check if a row is selected. – Willeke Apr 06 '18 at 12:24
  • Or does "no row selected" mean not clicked on a row? I was thinking about `selectedRowIndexes`. – Willeke Apr 06 '18 at 12:26
  • The table view can have a number of rows or no rows at all, the menu pops showing options for the register (row) regardless if there is even a row selected. I was looking to verify that a row is selected before displaying the menu, and not allowing the menu to show if there was no row selected. No row selected means there is no "blue frame" around the row when you click on it, the table view might have 3 rows of data but the click might happen outside the rows, therefore making selected row = -1, already posted a working answer I figured out. The duplicate was about a specific cell and not row – Ryuuzaki Julio Apr 06 '18 at 14:29
  • The "blue frame" is the clicked row. Selected rows have a blue background. – Willeke Apr 09 '18 at 22:02

1 Answers1

1

It was pretty easy:

Implement

NSMenuDelegate

and add this method:

func menuWillOpen(_ menu: NSMenu) {
        if myTableView.selectedRow < 0 {
            menu.cancelTrackingWithoutAnimation()
        }
    }
Ryuuzaki Julio
  • 369
  • 1
  • 14