2017-06-21 18 views
2

我想知道當一個窗口關閉,我實現了這個代碼將關閉:試圖知道當一個窗口在基於MacOS的文檔應用

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

回答

3

的問題存在,窗口屬性將總是返回零裏面viewDidLoadMethod。您需要在viewWillAppear方法中設置代理:

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

非常感謝您Leo! – Cue

+0

不客氣 –

相關問題