In my app I use NSMenu.popUp(positioning:at:in:)
for displaying a menu in response to the user clicking a button.
But it seems that when the menu is opened inside a modal window, all the menu items are always disabled.
Using NSMenu.popUpContextMenu(_:with:for:)
instead works. What's the reason and what's the difference between the two methods? According to the documentation, one is for opening "popup menus" and the other for opening "context menus", but I cannot see an explanation of the difference between the two.
@main
class AppDelegate: NSObject, NSApplicationDelegate {
func applicationDidFinishLaunching(_ aNotification: Notification) {
let window = NSWindow(contentViewController: ViewController())
NSApp.runModal(for: window)
}
}
class ViewController: NSViewController {
override func loadView() {
let button = NSButton(title: "Click", target: self, action: #selector(click(_:)))
view = NSView(frame: CGRect(x: 0, y: 0, width: 400, height: 400))
view.addSubview(button)
}
@objc func click(_ sender: Any?) {
let menu = NSMenu(title: "")
menu.addItem(withTitle: "asdf", action: #selector(asdf(_:)), keyEquivalent: "")
menu.addItem(withTitle: "bla", action: nil, keyEquivalent: "")
menu.items[0].target = self
menu.items[1].target = self
// NSMenu.popUpContextMenu(menu, with: NSApp.currentEvent!, for: view) // this works
menu.popUp(positioning: nil, at: .zero, in: view) // this doesn't work
}
@IBAction func asdf(_ sender: Any) {
print(0)
}
}