3

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

Cue
  • 2,952
  • 3
  • 33
  • 54

1 Answers1

4

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")
    }
}
Leo Dabus
  • 229,809
  • 59
  • 489
  • 571