【问题标题】:How to implement NSWindowRestoration in Swift?如何在 Swift 中实现 NSWindowRestoration?
【发布时间】:2014-06-10 00:50:12
【问题描述】:

我尝试在非基于文档的应用程序中在 Swift 中实现 NSWindowRestoration 协议。然而,restoreWindowWithIdentifier 方法永远不会在应用程序启动时被调用。谁能指出我的错误?

这是代码的子集(编译和运行良好):

class AppDelegate: NSObject, NSApplicationDelegate, NSWindowRestoration {

  var windowController : MyWindowController?

  func applicationDidFinishLaunching(aNotification: NSNotification?) {
    windowController = MyWindowController(windowNibName:"ImageSequenceView")
  }

  class func restoreWindowWithIdentifier(identifier: String!, state: NSCoder!, completionHandler: ((NSWindow!,NSError!) -> Void)!) {
    NSLog("restoreWindowWithIdentifier: \(identifier), state: \(state)")
  }

 }

class MyWindowController: NSWindowController {

  override func windowDidLoad() {
    super.windowDidLoad();
    window.restorationClass = AppDelegate.self
  }
}

提前致谢!

【问题讨论】:

  • 出于好奇,当您交换super.windowDidLoad() 的顺序并设置window.restorationClass 时会发生什么。
  • 抱歉,长途旅行。刚试过,但没有任何作用......
  • 当我使用 self.dynamicType 并确保我的系统首选项设置为恢复 Windows restoreWindowWithIdentifier 时,我的班级被调用。

标签: cocoa swift state-restoration


【解决方案1】:

你需要设置一个恢复类,一个标识符:

class MyWindowController: NSWindowController {
    override func windowDidLoad() {
        super.windowDidLoad()

        self.window?.restorationClass = type(of: self)
        self.window?.identifier = "MyWindow"
    }
}

extension MyWindowController: NSWindowRestoration {
    static func restoreWindow(withIdentifier identifier: String, state: NSCoder, completionHandler: @escaping (NSWindow?, Error?) -> Void) {
        if identifier == "MyWindow" {
            // Restore the window here
        }
    }
}

当然你也可以让另一个类恢复窗口,就像你试过的那样。在这种情况下,您需要将AppDelegate.self 分配为restorationClass

另外,请注意window restoration setting now defaults to "off",无论出于何种愚蠢的原因。

【讨论】:

  • 系统偏好设置窗口恢复设置默认为关闭也引起了我的注意。很容易迷失在代码中,想知道为什么没有按您预期的方式工作,直到您意识到这个复选框控制了一切。
猜你喜欢
  • 2015-11-30
  • 2014-09-07
  • 2016-11-27
  • 2017-04-30
  • 1970-01-01
  • 1970-01-01
  • 2023-02-16
  • 1970-01-01
  • 2018-02-22
相关资源
最近更新 更多