我试图知道窗口何时关闭,我实现了以下代码:
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
聚苯乙烯
我已经阅读了这个问题,没有找到解决方案:Handle close event of the window in Swift
最佳答案
问题是window属性在viewdidloadmethod中总是返回nil。您需要在viewwillappears方法中设置委托:
class ViewController: NSViewController, NSWindowDelegate {
override func viewWillAppear() {
super.viewWillAppear()
view.window?.delegate = self
}
func windowWillClose(_ aNotification: Notification) {
print("windowWillClose")
}
}