小编典典

尝试知道基于macOS Document的应用程序中的窗口何时关闭

swift

我试图知道何时关闭窗口,我实现了以下代码:

class ViewController: NSViewController, NSWindowDelegate {

    override func viewDidLoad() {
        super.viewDidLoad()

        let window: NSWindow? = view.window
        window?.delegate = self
    }

    func windowWillClose(_ aNotification: Notification) {
        print("windowWillClose")
    }

}

不幸的是,什么都没有发生,我该怎么办?

文件:https
:
//developer.apple.com/documentation/appkit/nswindow/1419400-willclosenotification


阅读 265

收藏
2020-07-07

共1个答案

小编典典

问题在于window属性将始终在viewDidLoadMethod内部返回nil。您需要在viewWillAppear方法中设置委托:

class ViewController: NSViewController, NSWindowDelegate {
    override func viewWillAppear() {
        super.viewWillAppear()
        view.window?.delegate = self
    }
    func windowWillClose(_ aNotification: Notification) {
        print("windowWillClose")
    }
}
2020-07-07