How do you add the ability to right click on a row in an NSOutlineView so you can say delete an object or some other activity. (ie Like when you right click on a folder in t
No need to subclass, its quite simple, and you can even customize the menu on the fly.
Declare an empty menu, set its delegate and set it on the outline views .menu property. As an added bonus this method works on both, outline and table views the same.
class OutlineViewController: NSViewController {
private let contextMenu = NSMenu(title: "Context")
override func viewDidLoad() {
super.viewDidLoad()
// other init stuff...
contextMenu.delegate = self
outlineView.menu = contextMenu
}
}
extension OutlineViewController: NSMenuDelegate {
func menuNeedsUpdate(_ menu: NSMenu) {
// Returns the clicked row indices.
// If the right click happens inside a selection, it is usually
// the selected rows, if it appears outside of the selection it
// is only the right clicked row with a blue border, as defined
// in the `NSTableView` extension below.
let indexes = outlineView.contextMenuRowIndexes
menu.removeAllItems()
// TODO: add/modify item as needed here before it is shown
}
}
extension NSTableView {
var contextMenuRowIndexes: IndexSet {
var indexes = selectedRowIndexes
// The blue selection box should always reflect the returned row indexes.
if clickedRow >= 0
&& (selectedRowIndexes.isEmpty || !selectedRowIndexes.contains(clickedRow)) {
indexes = [clickedRow]
}
return indexes
}
}