首页 > 解决方案 > NSDocument 选项卡窗口恢复

问题描述

这个问题处理基于文档的应用程序中的选项卡窗口恢复。

在允许用户创建和转换选项卡窗口的基于文档的 OSX 应用程序中,我需要保留和恢复每个窗口的“选项卡”状态。

目前,我的文档控制器恢复其文档窗口,但不恢复选项卡部署;我找回了单个窗口;我可以将所有内容合并为一个,但这太强硬了,因为他们以前的分组丢失了。

我的应用程序文档类的 -makeWindowControllers()函数是我影响新控制器的地方,它们是否应该级联,我认为这是错误的,在恢复期间:

//  Determine cascade based on state of application delegate
controller.shouldCascadeWindows = <app did receive applicationWillFinishLaunching>

所以在它完成启动之前它是错误的。

最后,我的窗口类的功能方法:

override func addTabbedWindow(_ window: NSWindow, ordered: NSWindow.OrderingMode) {
    super.addTabbedWindow(window, ordered: ordered)
    window.invalidateRestorableState()
}
override func moveTabToNewWindow(_ sender: Any?) {
    super.moveTabToNewWindow(sender)
    self.invalidateRestorableState()
}

override func encodeRestorableState(with coder: NSCoder) {
    if let tabGroup = self.tabGroup {
        let tabIndex = tabGroup.windows.firstIndex(of: self)
        coder.encode(tabIndex, forKey: "tabIndex" )
        Swift.print("<- tabIndex: \(String(describing: tabIndex))")
    }
}

override func restoreState(with coder: NSCoder) {
    let tabIndex = coder.decodeInt64(forKey: "tabIndex")
    Swift.print("-> tabIndex: \(tabIndex)")
}

在更改选项卡状态时,窗口还原状态无效。但是我不确定NSWindowRestoration协议的实现,当涉及文档控制器时,谁或什么需要实现协议。

我认为这是最后一个函数从未被调用的原因。我得到有关编码的调试输出,但在下一次应用程序执行期间,该restoreStore(coder:)函数从未被调用。

所以我想谁在这样的环境中实现这个窗口恢复协议是我的问题,或者是一个很好的例子。

标签: swiftmacosnswindowrestoration

解决方案


我的问题表明,对于基于文档的应用程序,您不需要任何特别的东西;我已经在SimpleViewer更新了我的原型,它具有这种支持和环境,它具有 Swift5,一个基于文档的应用程序支持选项卡。


推荐阅读