open multiple instances of a NSWindow

1.2k views Asked by At

I am building a chat application, for which I have an outlet for a NSWindow. Now I want to open multiple instances of the window. How do I do it? I'm not using window controller. makeKeyAndOrderFront: methods opens only one instance.

Please help me I couldn't find it anywhere

1

There are 1 answers

1
Thomas Horrobin On

So I know this question is old but I'm going to answer it anyway because I struggled with this and there's not a lot of information out there about it.

You need to keep every window in scope so it doesn't get garbage collected. You can do this with a collection of NSWindowControllers. I put this collection in AppDelegate.swift which is probably wrong, but I can't see anywhere else to put it, other than the main window controller, which would also be wrong.

You can declare it like this:

var exampleListOfWindows = [NSWindowController]()

You need to programmatically create new windows and then add them to your collection.

You can do that with a function like this:

func openNewWindow(someParameter: String) {

    let storyboard = NSStoryboard(name: "Main",bundle: nil)

    if let exampleViewController = storyboard.instantiateControllerWithIdentifier("exampleStoryboardId") as? ExampleViewController{

        let newWindow = NSWindow(contentViewController: exampleViewController)

        // you'll probably need to pass your window some data and because I hate myself I choose to do it like this
        exampleViewController.passSomeDataToNewWindowFunction(someParameter)

        newWindow.makeKeyAndOrderFront(self)

        let controller = NSWindowController(window: newWindow)
        exampleListOfWindows.append(controller)
        controller.showWindow(self)

    }
}