How can I show a NSMenu
next to my NSButton
after the button was clicked?
This is what I have so far:
@IBOutlet weak var BtnMenu: NSButton!
// Menu
let appMenu = NSMenu()
let showPrefsMenuItem = NSMenuItem(title: "Preferences...", action: #selector(VC.showPrefs(_:)), keyEquivalent: "")
let showAboutMenuItem = NSMenuItem(title: "About", action: #selector(VC.showAbout(_:)), keyEquivalent: "")
let quitAppMenuItem = NSMenuItem(title: "Quit", action: #selector(VC.quitApp(_:)), keyEquivalent: "")
override func viewDidLoad() {
super.viewDidLoad()
// Set up menu
self.appMenu.addItem(self.showPrefsMenuItem)
self.appMenu.addItem(self.showAboutMenuItem)
self.appMenu.addItem(NSMenuItem.separatorItem())
self.appMenu.addItem(self.quitAppMenuItem)
}
// Shows the app menu
@IBAction func openMenu(sender: NSButton) {
self.appMenu.popUpMenuPositioningItem(self.appMenu.itemAtIndex(0), atLocation: NSEvent.mouseLocation(), inView: nil)
}
But right now, the menu is shown on mouse position. Is there a way to show the menu next to the button?
Thanks.
This is how I solved it:
let p = NSPoint(x: sender.frame.origin.x, y: sender.frame.origin.y - (sender.frame.height / 2))
self.appMenu.popUp(positioning: nil, at: p, in: sender.superview)
In this case the menu is displayed under the clicked button.
Swift 3.
Show NSMenu under the button:
let p = NSPoint(x: 0, y: sender.frame.height)
appMenu.popUp(positioning: nil, at: p, in: sender)
Show NSMenu to the right of the button:
let p = NSPoint(x: sender.frame.width, y: 0)
appMenu.popUp(positioning: nil, at: p, in: sender)
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