Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handle close event of the window in Swift

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.

like image 994
Evgeniy Avatar asked Oct 19 '15 13:10

Evgeniy


3 Answers

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
}
like image 141
Thomas Alvarez Avatar answered Oct 25 '22 20:10

Thomas Alvarez


I was having the same query too, solved it using the method explained in detail here: Quit Cocoa App when Window Close using XCode Swift 3

It needs three steps:

  1. Conform toNSWindowDelegate in your ViewController class
  2. Override viewDidAppear method
  3. Add windowShouldClose method

The added code should look like this:

class ViewController: NSViewController, NSWindowDelegate {
    // ... rest of the code goes here
    override func viewDidAppear() {
        self.view.window?.delegate = self
    }
    func windowShouldClose(_ sender: Any) {
        NSApplication.shared().terminate(self)
    }
}
like image 35
Nabeel Khan Avatar answered Oct 25 '22 19:10

Nabeel Khan


You can use the NSWindowDelegate protocol in your ViewController class. (See the documentation here)

To make your class conform to the protocol:

class ViewController: NSObject, NSWindowDelegate

To detect when the window's close button has been clicked, use windowShouldClose:

From the doc:

Tells the delegate that the user has attempted to close a window [...]

In this method, you can use NSAlert to prompt the user on whether or not they really want to close the window.

EDIT (in response to @Mr Beardsley's comment)

To make your ViewController the delegate, use:

window.delegate = self

Where self is the ViewController and window is the window you're using. You can put this in viewDidLoad:.

like image 3
Arc676 Avatar answered Oct 25 '22 18:10

Arc676