【问题标题】:Trying to know when a window closes in a macOS Document based application试图了解基于 macOS 文档的应用程序中的窗口何时关闭
【发布时间】:2017-06-21 20:11:11
【问题描述】:

我想知道窗口何时关闭,我实现了这段代码:

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

PS 我已经阅读了这个问题但没有找到解决方案:Handle close event of the window in Swift

【问题讨论】:

    标签: swift cocoa


    【解决方案1】:

    问题在于 window 属性在 viewDidLoadMethod 中总是返回 nil。您需要在 viewWillAppear 方法中设置委托:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多