swiftcocoaappkitnswindowcontrollernsmenuitem

How to get multiple windows to perform the same menu item action?


I have a Cocoa app which supports multiple windows.

I already know how to get the main window to perform actions for any of the NSMenuItem from NSMenu and including the NSToolbarItem from the NSToolbar.

class MainWindowController: NSWindowController {
    // ...
    @IBAction func doSomethingIncredible(_ sender: Any?) {
        // ...
    }
}

That is easy for a single window app but my app supports multiple windows.

But how can I get other windows apart from the main window to access and even validate the NSMenuItem from NSMenu?

An example of this is Safari. It supports multiple windows. You can select Open Location...(⌘L), New Tab (⌘T), Show Sidebar (⇧⌘L) etc. It does the action on the focused window. It is not tied to the main window. It can be done on any windows. How can I do this for my app?

class AnotherWindowController: NSWindowController {
    // ...
    @IBAction func doSomethingIncredible(_ sender: Any?) {
        // ...
    }
}

How can the MainWindowController and the AnotherWindowController perform the same action from one of the NSMenuItem from NSMenu when one of them is the key focused window?


Solution

  • Rather than hard-connecting the menu item to a specific controller connect it to the First Responder (the red cube).

    The first object in the responder chain which responds to the seclector – usually the frontmost window – catches the action and executes it.