Open New Window in Swift

15.2k views Asked by At

I am trying to open a new window in my Swift application but I cannot get it to open.

class AppDelegate: NSObject, NSApplicationDelegate 
{
    func applicationDidFinishLaunching(aNotification: NSNotification)
    {
        openMyWindow()
    }

    func openMyWindow()
    {
        if let storyboard = NSStoryboard(name: "Main",bundle: nil)
        {
            if let vc = storyboard.instantiateControllerWithIdentifier("MyList") as? MyListViewController
            {
                var myWindow = NSWindow(contentViewController: vc)
                myWindow.makeKeyAndOrderFront(self)
                let controller = NSWindowController(window: myWindow)

                controller.showWindow(self)

            }
        }
    }
}

I have set the Storyboard ID in IB.

I have traced the code and it does get into the window opening code but it doesn't do anything.

BTW I do have a default storyboard entry point set and that default window opens OK but I need to have a second window open and that is what is not working.

1

There are 1 answers

0
mangerlahn On BEST ANSWER

After the openMyWindow() method is executed, the windowController will be released and consequently the window is nil. That's why it is not there.

You have to hold the window in you class to keep it alive, then the window will be visible.

var windowController : NSWindowController?