Pablo
Pablo

Reputation: 29529

How to access NSViewController from app delegate?

In my macOS application I have menu items, which are replicated also in main UI. Application is consisted of main window with its delegate and single view along with its view controller. In app delegate I capture menu item click action, then I need to send this event to my view controller in order to take appropriate actions and also update main UI.

Question is how to access my view controller (NSViewController) from app delegate?

Upvotes: 6

Views: 2098

Answers (2)

vadian
vadian

Reputation: 285290

Actually you don't need a reference to the controller. There is First Responder

  • Declare the IBActions
  • In Interface Builder connect the menu items to the First Responder (red cube) of the target object and choose the appropriate action.

The action will be executed in the first object of the responder chain which implements the action.

Upvotes: 0

Fabian
Fabian

Reputation: 5358

If you have window as an IBOutlet you can do

var rootViewController: MyViewController? {
    return window!.contentViewController as? MyViewController
}

func sendPressed(_ sender: Any?) {
   rootViewController?.sendPressed()
}

If you don‘t have a window variable you can get it through

NSApplication.shared.orderedWindows.first!

Upvotes: 3

Related Questions