繁体   English   中英

NSDocument:如何保存和恢复文档的窗口位置?

[英]NSDocument: how do you save & restore a document's window position?

我有一个基于NSDocument的应用程序,我希望在重新打开文档时保存和恢复我的窗口位置。 Apple关于此的文档相当稀疏,但我能够拼凑起来的是,在某些时候,应用程序中的某些东西需要调用NSWindow.setFrameUsingName()NSWindow.setFrameAutosaveName()

我还没想到的是,这需要发生什么,以及需要做些什么。 例如,这根本不起作用:

// In my NSDocument class    
override func windowControllerDidLoadNib(aController: NSWindowController) {
    super.windowControllerDidLoadNib(aController)

    // Add any code here that needs to be executed once the windowController has loaded the document's window.
    aController.window?.setFrameUsingName("MainWindow")
    aController.window?.setFrameAutosaveName("MainWindow")
}

我已经阅读了各种不同的文档或论坛答案,指出awakeFromNib()是另一个要做的事情,但我也无法做到这一点。

我也很困惑/担心这会在某种程度上受到Auto Layout的影响或者我在Interface Builder中做错了 - 例如,这就是我在IB中设置窗口的方式:

我并不特别希望我的窗口居中,但其他选项似乎将它锁定在固定的水平或固定垂直位置,我也不是真的想要。 让我的窗口居中的一个副作用是我的文档窗口不再级联,我既不想要也不能似乎停止发生(注意windowController.shouldCascadeWindows = true也没有帮助)。

那么 - 这里发生了什么? 我发现关于这个主题的知识特别不清楚或误导,并且可能已经过时了2015年的可可开发,所以对此进行现代复习会很棒。

步骤1:在IB中,为窗口指定自动保存名称。

在此输入图像描述

第2步:没有第2步。

设置窗口框架自动保存名称的最简单位置可能在您的NSDocument实现中。

如果覆盖makeWindowControllers()作为实现的一部分,则手动创建窗口控制器,因此可以在其中设置名称:

override func makeWindowControllers() {
    let storyboard = NSStoryboard(name: NSStoryboard.Name("MyDocumentStoryboard"), bundle: nil)
    let windowController = storyboard.instantiateController(withIdentifier: NSStoryboard.SceneIdentifier("MyDocument Window Controller")) as! MyDocumentWindowController

    // this assumes you have a stored property or a computed property `someUniqueIdentifier` that is as unique as possible for your document
    // and that you store on disk together with the rest of the document properties
    windowController.windowFrameAutosaveName = NSWindow.FrameAutosaveName(rawValue: someUniqueIdentifier)

    self.addWindowController(windowController)
}

如果通过覆盖windowNibName实例化文档窗口,则应该覆盖方法windowControllerDidLoadNib(_:) ,以在窗口上设置自动保存名称。 我没有测试过这段代码,但我认为它会起作用:

func windowControllerDidLoadNib(_ windowController: NSWindowController) {
    // this assumes you have a stored property or a computed property `someUniqueIdentifier` that is as unique as possible for your document
    // and that you store on disk together with the rest of the document properties
    windowController.windowFrameAutosaveName = NSWindow.FrameAutosaveName(rawValue: someUniqueIdentifier)
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM