Cocoa: How to have a context menu when you right-click on a cell of NSTableView
A Swift 4 version of Rob's answer:
Add the menu:
let menu = NSMenu()
menu.addItem(NSMenuItem(title: "Edit", action: #selector(tableViewEditItemClicked(_:)), keyEquivalent: ""))
menu.addItem(NSMenuItem(title: "Delete", action: #selector(tableViewDeleteItemClicked(_:)), keyEquivalent: ""))
tableView.menu = menu
The functions:
@objc private func tableViewEditItemClicked(_ sender: AnyObject) {
guard tableView.clickedRow >= 0 else { return }
let item = items[tableView.clickedRow]
showDetailsViewController(with: item)
}
@objc private func tableViewDeleteItemClicked(_ sender: AnyObject) {
guard tableView.clickedRow >= 0 else { return }
items.remove(at: tableView.clickedRow)
tableView.reloadData()
}
There's no need to muck about with event handling, all you have to do to assign a contextual menu is set the table view's menu
outlet to point to the NSMenu
object that you want to use for the contextual menu.
You can do this in Interface Builder by dropping an NSMenu
object into your nib file and control-dragging from the table view to the menu to set the outlet.
Alternatively, you can use the -setMenu:
method of NSTableView
(inherited from NSResponder
) to assign the menu programmatically.