Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Popup menu implementation from NSButton

How should I go about it?

I was thinking about...

[NSMenu popUpContextMenu:menu withEvent:event forView:(NSButton *)sender];
like image 310
Dr.Kameleon Avatar asked Mar 15 '12 08:03

Dr.Kameleon


2 Answers

Yup.

On button action call

[NSMenu popUpContextMenu:menu withEvent:event forView:(NSButton *)sender];

where

  • menu : menu you want to show
  • sender : button you clicked
  • event : a new NSEvent you create

When you create the new NSEvent, specify the location as to where you want the popup menu to be shown.

like image 50
arun.s Avatar answered Oct 28 '22 09:10

arun.s


Swift version of accepted answer

@IBAction func actionOccurred(sender: NSButton) {
    if let event = NSApplication.sharedApplication().currentEvent {
        NSMenu.popUpContextMenu(sender.menu!, withEvent: event, forView: sender)
    }
}

Updated answer

Add NSMenu to the NSViewController in the storyboard as seen in the image

Image

Connect the Outlet

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)

jj

Add IBAction

@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)
}
like image 22
Kaunteya Avatar answered Oct 28 '22 11:10

Kaunteya