我试图知道何时关闭窗口,我实现了以下代码:
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
问题在于window属性将始终在viewDidLoadMethod内部返回nil。您需要在viewWillAppear方法中设置委托:
class ViewController: NSViewController, NSWindowDelegate { override func viewWillAppear() { super.viewWillAppear() view.window?.delegate = self } func windowWillClose(_ aNotification: Notification) { print("windowWillClose") } }