How do you open a closed window created in a storyboard in OS X

My question is very important to this question, but the answer doesn't seem to work with Swift / Storyboards. Cocoa: programmatically show main window after closing it with X

Basically, I have a more or less standard application with menu, window and ViewController. If the user closes the window while the application is running, how do I reopen it?

I have created an action in the application's debit that connects to the "Open" menu item. Inside this function, I would like to make sure the window is visible. So if the user closed it, it should reappear. But I cannot figure out how to access the closed window. The storyboard doesn't seem to allow me to create an exit for my window in my application sub.

+3


source to share


1 answer


It's pretty easy to archive, not even a neat solution. Add a new property to your application's delegate for your main window controller. In the following example, I am calling a controller MainWindowController

.

@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
    var mainWindowController: MainWindowController? = nil
    func applicationShouldHandleReopen(sender: NSApplication, hasVisibleWindows flag: Bool) -> Bool {
        mainWindowController?.window?.makeKeyAndOrderFront(self)
        return false
    }
}

      

In the initialization of the main window controller, I register the controller with the application delegate:



class MainWindowController: NSWindowController {
    override func windowDidLoad() {
        super.windowDidLoad()
        // ...initialisation...
        // Register the controller in the app delegate
        let appDelegate = NSApp.delegate as! AppDelegate
        appDelegate.mainWindowController = self
    }
}

      

That's it, works great for me.

+4


source







All Articles