How do I show a new/additional NSViewController in swift macOS App with no modal

241 Views Asked by At

step1. I new a project in Xcode 13.2.1 with macOS App, swift and storyboard

step2. The default NSViewController named InitialViewController. I add a button named open.

step3. I add a NSViewController named NewViewController and storyboard ID is NewView.

step4. I connected the button action and add the code shown below to show NewViewController with no modal.

    @IBAction func click(_ sender: Any) {

        let newView = (self.storyboard!.instantiateController(withIdentifier: "NewView") as! NewViewController)
        let windowVC = NSWindowController(window: newView.view.window)
        windowVC.showWindow(nil)
    }

step5. I run the App and click the button, and then I found that the NewViewController didn't show.

How do I show a new/additional NSViewController with no modal? Could you provide a sample code? Thanks in advance.

2

There are 2 best solutions below

0
vadian On

If the NSViewController doesn't have a parent NSWindowController in Interface Builder there is no window and you have to create one either in IB or in code.

For example in code add in AppDelgate

let windowController : NSWindowController = {
    return NSWindowController(
        window: NSWindow(contentRect: NSRect(origin: .zero, size: CGSize(width: 700.0, height: 450.0)),
                         styleMask: [.titled, .resizable, .miniaturizable, .closable],
                         backing: .buffered,
                         defer: false))
}()

And change the IBAction to

@IBAction func click(_ sender: Any) {

    let newViewController = self.storyboard!.instantiateController(withIdentifier: "NewView") as! NewViewController
    windowController.contentViewController = newViewController
    windowController.showWindow(nil)
}
0
marky1 On

I followed vadian's sample code and I modified the IBAction shown below. The NewViewController with no modal can be showed normally.

@IBAction func click(_ sender: Any) {

    let newView = (self.storyboard!.instantiateController(withIdentifier: "NewView") as! NewViewController)
    let windowVC = NSWindowController(window: NSWindow(contentViewController: newView))
    windowVC.showWindow(nil)
}