Handle close event of the window in Swift

Evgeniy picture Evgeniy · Oct 19, 2015 · Viewed 15.3k times · Source

How to handle close event of the window using swift, for example, to ask "Are you sure you want to close the form?"

enter image description here

The form will be closed in the case "yes" and not closed in the case "no". Showing message box is not a problem for me.

viewWillDisappear() works for minimizing also, but I need only close event.

Thanks.

Answer

Thomas Alvarez picture Thomas Alvarez · Nov 20, 2015

Like said above, you should make the ViewController an NSWindowDelegate, but you should handle windowWillClose, not windowShouldClose. windowShouldClose is to determine if the window is able to close or not, not an event that the window is actually closing.

I also found that you need to set up the delegate in viewDidAppear, not viewDidLoad. For me self.view.window wasn't defined yet in viewDidLoad.

override func viewDidAppear() {
    self.view.window?.delegate = self
}