Connect to ViewController from AppDelegate (Swift)

You can access the mainWinow property and the contentViewController property to create a reference to your custom ViewController class. This is similar to the iOS rootViewController property.

let rootViewController = NSApplication.shared().mainWindow?.windowController?.contentViewController as! ViewController

Now you can use this reference to access IBOutlets on your main storyboard from your AppDelegate.

rootViewController.myTextView.textStorage?.mutableString.setString("Cats and dogs.")

This is good for a simple app with one Window with one ViewController.


It seems that AppDelegate can connect to objects only within Application Scene in a storyboard. If you want to get a ViewController, instantiate it from a storyboard.

sample:

@IBAction func menuAction(sender: AnyObject) {
    if let storyboard = NSStoryboard(name: "Main", bundle: nil) {
        let controller = storyboard.instantiateControllerWithIdentifier("VC1") as NSViewController

        if let window = NSApplication.sharedApplication().mainWindow {
            window.contentViewController = controller // just swap
        }
    }
}