2

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?

UKDataGeek
  • 6,338
  • 9
  • 46
  • 63

1 Answers1

6

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: ""))
    }
}
Kevin Low
  • 2,672
  • 16
  • 17
  • How do I do that? It seems to error when I try that. let dockMenu = NSApplication.sharedApplication().delegate.dockMenu says there is no such property if I have added the var docMenu = NSMenu() property just after the opening AppDelegate – UKDataGeek Jun 24 '16 at 14:48
  • ah forgot to cast to AppDelegate. – UKDataGeek Jun 24 '16 at 14:53
  • 1
    It sounds like `dockMenu` is somehow not visible. I have added some sample code. Although the sample code shows passing through properties, I have tried using the `NSApplication.sharedApplication()` variation with success. – Kevin Low Jun 24 '16 at 15:19
  • Thanks so much Kevin. Works wonderfully. Appreciate the help – UKDataGeek Jun 24 '16 at 16:45