Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Show NSMenu next to NSButton in Swift macOS

Tags:

macos

swift

cocoa

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.

like image 787
daB0bby Avatar asked Apr 11 '16 21:04

daB0bby


Video Answer


2 Answers

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.

like image 151
daB0bby Avatar answered Sep 28 '22 08:09

daB0bby


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)
like image 24
Дмитрий Боровиков Avatar answered Sep 28 '22 08:09

Дмитрий Боровиков