如何重新打开OS X中故事板中创建的关闭窗口

时间:2015-06-02 11:59:36

标签: macos swift xcode-storyboard

我的问题对于这个问题至关重要,但答案似乎不适用于Swift / Storyboards。 Cocoa: programmatically show the main window after closing it with X

基本上,我有一个或多或少的默认应用程序,包含菜单,窗口和ViewController。如果用户在应用程序运行时关闭窗口,我该如何重新打开它?

我在app中创建了一个动作委托连接到“打开”菜单项。在这个函数中,我想确保窗口是可见的。因此,如果用户关闭它,它应该重新出现。但我无法弄清楚如何访问关闭的窗口。故事板似乎不允许我在我的应用代表中为我的窗口创建一个插座。

1 个答案:

答案 0 :(得分:4)

归档非常简单,即使它不是一个优雅的解决方案。将新属性添加到主窗口控制器的应用程序委托中。在以下示例中,我调用控制器MainWindowController

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

在主窗口控制器的初始化中,我在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
    }
}

这就是全部,对我来说非常适合。