簡體   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