问题
I have implemented a dock menu in my Mac app via the Application delegate method:
func applicationDockMenu(sender: NSApplication) -> NSMenu? {
let newMenu = NSMenu(title: "MyMenu")
let newMenuItem = NSMenuItem(title: "Common Items", action: "selectDockMenuItem:", keyEquivalent: "")
newMenuItem.tag = 1
newMenu.addItem(newMenuItem)
return newMenu
Is there a way I can add items to the menu from within my View Controller - I can't seem to find a method in my NSApplication object. Is there another place I should look?
回答1:
Since applicationDockMenu: is a delegate method, having an instance method add menu items would conflict with the delegate return.
What you could do is make the dock menu a property/instance variable in your application delegate class. This way, your view controller could modify the menu either by passing the reference to the menu from your application delegate to your view controller (which you would have a dockMenu property) or referencing it globally (less recommended).
class AppDelegate: NSObject, NSApplicationDelegate {
@IBOutlet weak var window: NSWindow!
var dockMenu = NSMenu(title: "MyMenu")
func applicationDidFinishLaunching(aNotification: NSNotification) {
if let viewController = ViewController(nibName: "ViewController", bundle: nil) {
viewController.dockMenu = self.dockMenu
self.window.contentViewController = viewController
}
}
func applicationDockMenu(sender: NSApplication) -> NSMenu? {
return self.dockMenu
}
class ViewController: NSViewController {
var dockMenu: NSMenu?
// Button action
@IBAction func updateDockMenu(sender: AnyObject) {
self.dockMenu?.addItem(NSMenuItem(title: "An Item", action: nil, keyEquivalent: ""))
}
}
来源:https://stackoverflow.com/questions/38014076/adding-items-to-the-dock-menu-from-my-view-controller-in-my-cocoa-app