Connect to ViewController from AppDelegate (Swift)

10,762

Solution 1

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
        }
    }
}

Solution 2

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.

Solution 3

I was stuck trying to do this same thing recently and managed to get the event I needed to update my view by creating the @IBAction in my ViewController and control dragging to my Application's First Responder (above the menu in my storyboard view).

Here's the question that got me out of the woods: Application Menu Items Xcode

And thanks to Bluedome for the suggestion to connect it to First Responder's action.

Share:
10,762
Michael Knudsen
Author by

Michael Knudsen

Data Manager, Aarhus University Hospital, Denmark.

Updated on July 23, 2022

Comments

  • Michael Knudsen
    Michael Knudsen almost 2 years

    I have created a new OS X Cocoa Application using the standard Xcode Swift template (using StoryBoards).

    I have implemented an IBAction in AppDelegate.swift to handle when the users selects "Open..." from the "File" menu. If the chosen file is a valid image file, I create an NSImage which I then want to display in the view of ViewController.

        @IBAction func openFile(sender: NSMenuItem) {
        var openPanel = NSOpenPanel()
        openPanel.beginWithCompletionHandler { (result :Int) -> Void in
            if result == NSFileHandlingPanelOKButton {
                if let imageURL = openPanel.URL {
                    let image = NSImage(contentsOfURL: imageURL)
                    // PRESENT image IN THE VIEW CONTROLLER
                }
            }
        }
    

    However, I don't see any way to connect to ViewController from AppDelegate. I have only managed to find suggestions that I should look at self.window! in AppDelegate, but there is no such thing as a window in AppDelegate.

    Thanks, Michael Knudsen