Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding a NSMenu to a NSTableCellView which pops up on right click

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!

like image 924
ixany Avatar asked Mar 10 '23 00:03

ixany


1 Answers

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)")
}
like image 188
Code Different Avatar answered Mar 13 '23 11:03

Code Different