How should I go about it?
I was thinking about...
[NSMenu popUpContextMenu:menu withEvent:event forView:(NSButton *)sender];
Yup.
On button action call
[NSMenu popUpContextMenu:menu withEvent:event forView:(NSButton *)sender];
where
menu
: menu you want to show sender
: button you clickedevent
: a new NSEvent
you createWhen you create the new NSEvent
, specify the location as to where you want the popup menu to be shown.
Swift version of accepted answer
@IBAction func actionOccurred(sender: NSButton) {
if let event = NSApplication.sharedApplication().currentEvent {
NSMenu.popUpContextMenu(sender.menu!, withEvent: event, forView: sender)
}
}
Add NSMenu to the NSViewController in the storyboard as seen in the image
Right-click on the button in the storyboard and connect the menu outlet to the menu that we have just added to the storyboard(Where arrow points in the image)
@IBAction func menuClicked(_ sender: NSButton) {
var location = NSEvent.mouseLocation
location.x -= 10; location.y -= 10 // Menu appears below the button
let menu = sender.menu!
menu.popUp(positioning: menu.item(at: 0), at: location, in: nil)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With