How do I open another window in macOS in Swift with Cocoa

Viewed 12589

I am working on a macOS app that presents a list of customer master records in a table view. Double-clicking a row in the table view should open a new window where the user can view and edit the customer information.

This is an Xcode 8.3.3 project using a storyboard and Swift.
It is not a document or core data app.

I have the main window working up to the point where the table view is displaying the records correctly and the associated view controller is receiving the double-click events and logging them to the console.

I have created an additional window controller and view for the edit window and verified its basic functionality by temporarily marking it as the initial controller.

What I haven't been able to figure out is how to display a new instance of that window when the user double-clicks a row.

Thanks to @Joshua Nozzi I'm closer. Here is the code at this point.

let storyboard = NSStoryboard(name: "Main", bundle: nil)
if let windowController = storyboard.instantiateController(withIdentifier: "xyzzy") as? NSWindowController
{
  windowController.showWindow(self)
}

It's generating a

(Storyboard: 0x620000000680) doesn't contain a controller with identifier 'xyzzy'

error.

3 Answers

Additionally, to open new window, this code can help you

windowController.contentViewController = tabViewController

The full code is like that i used it in my project:

@objc func openApplicationView(_ sender: Any?) {
    let mainStoryBoard = NSStoryboard(name: "Main", bundle: nil)
    let tabViewController = mainStoryBoard.instantiateController(withIdentifier: "tabView") as? TabViewController
    let windowController = mainStoryBoard.instantiateController(withIdentifier: "secondWindow") as! TabViewWindowController
    windowController.showWindow(self)
    windowController.contentViewController = tabViewController
}

It can helpful if you've closed the mainWindow. So you need to add one windowController and tabViewController(you can use normal view controller) in your own underlying storyboard.

In my side the tabViewController has been extended by NSTabViewController and tab view component has been bound with this class.

Note: I've also added the windowController in my Main.storyboard as a component and identified to use then on coding side.

Related