Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

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

I have created an action in the app delegate the connects to the "Open" Menu Item. Within this function, I would like to ensure that the window is visible. So if the user has closed it, it should reappear. But I cannot figure out how to access the closed window. Storyboard does not seem to allow me to create an outlet for my Window in my app delegate.

like image 656
Fletcher Moore Avatar asked Jun 02 '15 11:06

Fletcher Moore


1 Answers

This is quite simple to archive, even it is not an elegant solution. Add a new property to your app delegate for your main window controller. In the following example, I call the 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 initialisation of the main window controller I register the controller in the app 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 is all, works perfectly for me.

like image 149
Flovdis Avatar answered Oct 25 '22 09:10

Flovdis