5

I want to popup a NSMenu when the user right-clicks on a NSTableCellView within a NSTableView.

let cell = myTableView.make(withIdentifier: "myCustomTableCellView", owner: self) as! MyTableCellView // subclass of NSTableCellView

let menu = NSMenu()
menu.autoenablesItems = false
menu.addItem(NSMenuItem(title: "Test", action: nil, keyEquivalent: ""))

cell.menu = menu

But the menu pops not up if the user clicks on the cell.

I couldn’t find any sendActionOn methods or something similar.

Would be great if someone could help!

ixany
  • 5,433
  • 9
  • 41
  • 65

1 Answers1

8

No need to do anything fancy. You can design your menu in Interface Builder.

  1. Drag a Menu from the Object Library to your View Controller
  2. Ctrl-drag from the Table View to this menu and connect it to the menu outlet

Connect Table View to Menu

  1. Connect the menu items with IBActions in your View Controller:

Say you have 3 actions on your right-click menu

@IBAction func menuAction1(_ sender: Any) {
    print("You clicked Item 1 for row \(self.tableView.selectedRow)")
}

@IBAction func menuAction2(_ sender: Any) {
    print("You clicked Item 2 for row \(self.tableView.selectedRow)")
}

@IBAction func menuAction3(_ sender: Any) {
    print("You clicked Item 3 for row \(self.tableView.selectedRow)")
}
Code Different
  • 90,614
  • 16
  • 144
  • 163
  • Thank you! It basically works, but this way every type of TableCellView within the TableView has that menu. My question was how to add a NSMenu (programatically) to a specific TableCellView? – ixany Jan 28 '17 at 18:37
  • While this works at showing the menu, right-click doesn't trigger row selection on the tableview, so `self.tableView.selectedRow` is always going to be `-1`, unless the row is preselected by normal (left) click first. – Inn0vative1 Feb 08 '17 at 03:04
  • 4
    Should use `self.tableView.clickedRow` to get the clicked row. – Inn0vative1 Feb 08 '17 at 03:11