Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

macos

swift

cocoa

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?

like image 732
UKDataGeek Avatar asked Dec 14 '25 15:12

UKDataGeek


1 Answers

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: ""))
    }
}
like image 57
Kevin Low Avatar answered Dec 17 '25 03:12

Kevin Low