简体   繁体   中英

Trying to know when a window closes in a macOS Document based application

I'm trying to know when a window closes, I implemented this code:

class ViewController: NSViewController, NSWindowDelegate {

    override func viewDidLoad() {
        super.viewDidLoad()

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

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

}

Unfortunately nothing happens, what could I made wrong?

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

PS I already read this question without to find a solution: Handle close event of the window in Swift

The problem there is that the window property will always return nil inside viewDidLoadMethod. You need to set the delegate inside viewWillAppear method:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM