Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Open New Window in Swift

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.

like image 930
iphaaw Avatar asked Jun 18 '15 17:06

iphaaw


People also ask

How do I open windows in Swift?

Step 1: Write a basic program in Swift with your favorite editor. Step 2: Open "Swift for Windows 1.6" and click 'Select File' to choose your file. Step 3: Click 'Compile' to compile your program. Step 4: Click 'Run' to run on Windows.

How do I create a new window in Xcode?

The Xcode project window is your primary interface for viewing, editing, and managing all parts of your project. You can configure it to fit your work style and adjust it as you work on different tasks. The main window opens when you create or open a project. To open additional main windows, choose File > New > Window.

How to add a new View in Xcode?

Click on background of Main. storyboard . Search and select ViewController from object library at the utility window. Drag and drop it in background to create a new ViewController .


1 Answers

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?
like image 68
mangerlahn Avatar answered Oct 03 '22 06:10

mangerlahn