Two windows from the beginning

(macOS, Swift, storyboards)


How can I have two windows open from the beginning? (without clicking any button)


What I have tried:


1- CREATE A NEW WINDOW

- Main.storyboard I have a Window Controller from the library

- I have created a New document Cocoa Class SecondViewController

- Main.storyboard > I select View Controller. In Identity Inspector I select Class SecondViewController


2- MAKE IT LAUNCH FROM THE BEGINNING

- AppDelegate.swift inside applicationDidFinishLaunching:

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

let windowController = storyboard.instantiateController(withIdentifier: "MySecondController") as! NSWindowController

windowController.showWindow(self)


- I think my problem is how to identify MySecondController in Main.storyboard

I tried to select Window inside Window Controller. Then go to Identity Inspector and Identifier. But when I run, it does not appear. How should I identify that second window, where exactly should I put MySecondController name? Or perhaps I have not created well the second window?

Accepted Reply

It is even simpler with storyboard.


All you have to do is put this in applicationDidFinishLaunching.

Note: SecondWindowID is the stroryboard ID of the second windowController.


    func applicationDidFinishLaunching(_ aNotification: Notification) {
        // Insert code here to initialize your application
        let storyboard = NSStoryboard(name: "Main", bundle: nil)
        if let windowController = storyboard.instantiateController(withIdentifier: "SecondWindowID") as? NSWindowController {
          windowController.showWindow(self)
        }
    }

Replies

Here is my setup, in such a case.


The second window uses a windowController


I have a global (in a singleton in fact) for the secondController:


secondController = SecondController() // In fact, initialized with some parameters


class SecondController: NSWindowController

// In its init, I call

self.init(windowNibName: NSNib.Name(rawValue: "TheNibName"))


Now, to open the window, I just call

secondController.showWindow(self) // nil ou self



Hope that helps. Tell me if you need more details.

Thank you Claude31. Can you specify where do you put each part of the code, please? Remember that I use storyboard. (I am not familiar with the previous way)

It is even simpler with storyboard.


All you have to do is put this in applicationDidFinishLaunching.

Note: SecondWindowID is the stroryboard ID of the second windowController.


    func applicationDidFinishLaunching(_ aNotification: Notification) {
        // Insert code here to initialize your application
        let storyboard = NSStoryboard(name: "Main", bundle: nil)
        if let windowController = storyboard.instantiateController(withIdentifier: "SecondWindowID") as? NSWindowController {
          windowController.showWindow(self)
        }
    }