Adding a NSMenu to a NSTableCellView which pops up on right click
Asked Answered
S

1

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!

Silvasilvain answered 27/1, 2017 at 22:10 Comment(0)
B
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)")
}
Bobker answered 28/1, 2017 at 17:22 Comment(3)
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?Silvasilvain
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.Towland
Should use self.tableView.clickedRow to get the clicked row.Towland

© 2022 - 2025 — McMap. All rights reserved.