ViewController.swift
import Cocoa class ViewController: NSViewController { var selectData:String = "" @IBOutlet weak var menuButton: NSButton! @objc func setContextMenu(_ sender: NSMenuItem) { if(sender.tag == 1){ //edit print("edit"+self.selectData) }else if(sender.tag == 2){ //delete print("delete"+self.selectData) } } func popupMenuForValue(data:String) -> NSMenu { var showText:[String] = [] showText.append("edit") showText.append("delete") let theMenu = NSMenu(title: "Menu") // Not used in fact theMenu.autoenablesItems = false // allows to deactivate some items var i=1 for text in showText { let item = NSMenuItem(title: text, action: #selector(setContextMenu(_:)), keyEquivalent: "") item.tag=i theMenu.addItem(item) i+=1 } return theMenu } @objc func rightClick(_ sender:ClickRecognizer){ self.selectData = sender.data let theMenu = popupMenuForValue(data:sender.data) NSMenu.popUpContextMenu(theMenu, with:NSApp.currentEvent!, for: sender.view! ) } override func viewDidLoad() { let ges = ClickRecognizer() ges.target = self ges.data = "u07500499" ges.buttonMask = 0x2 ges.numberOfClicksRequired = 1 ges.action = #selector(rightClick(_:)) menuButton.addGestureRecognizer(ges) } }
ClickRecognizer.swift
import Cocoa class ClickRecognizer: NSClickGestureRecognizer { var data:String = "" }