【问题标题】:NSDocument: how do you save & restore a document's window position?NSDocument:如何保存和恢复文档的窗口位置?
【发布时间】:2015-07-16 18:53:52
【问题描述】:

我有一个基于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() 是另一个可以执行此操作的领域,但我也无法使其发挥作用。

我也很困惑/担心这会以某种方式受到自动布局或我在 Interface Builder 中做错的事情的影响 - 例如,这是我在 IB 中设置窗口的方式:

我并不特别希望我的窗口居中,但其他选项似乎将其锁定在固定的水平或固定的垂直位置,我也不是很想要。让我的窗口居中的一个副作用是我的文档窗口不再级联,我既不想也似乎无法阻止这种情况发生(请注意,windowController.shouldCascadeWindows = true 也无济于事)。

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

【问题讨论】:

    标签: swift cocoa osx-yosemite nsdocument


    【解决方案1】:

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

    第 2 步:没有第 2 步。

    【讨论】:

    • 我发现这有两个问题:它使每个 NSDocument 窗口都使用相同的原点,并且它不会恢复窗口的大小,只是恢复原点。我将框架存储在我的文档数据中,但它总是在默认位置打开文档窗口,然后移动它,这看起来真的很糟糕。必须有一个标准的解决方案。
    • 与@SarahR 相同的问题
    【解决方案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)
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-04-27
      • 2023-03-16
      • 2012-03-29
      • 1970-01-01
      • 2022-01-26
      • 2011-02-20
      • 1970-01-01
      相关资源
      最近更新 更多