Adding Items to the Dock Menu from my View Controller in my Cocoa App

孤者浪人 提交于 2021-01-27 17:56:06

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!