8
votes

I am creating an OSX app with swift version 2.2. I need to execute a method when the user clicking the close button on top left corner of my app, I am new in Cocoa programming anyone now which is the event executing when clicking close button (see the image).

Close button

My purpose is when i keep my app on dock it is not open after clicking close button(the black dot under app is showing after clicking close button), but in a case right click and force quit on it then clicking app on dock it will re open fine. I think by giving the below given code inside close button event will solve my problem.

NSApplication.sharedApplication().terminate(self)
2
The close button isn't the close button of the app, it is the close button of the window.Willeke
in my app only have one window that's why i ask for that.Ben Rockey

2 Answers

11
votes
func applicationShouldTerminateAfterLastWindowClosed(sender: NSApplication) -> Bool {
    NSApplication.sharedApplication().terminate(self)
    return true
}

Inside appdeligate work for me.

For Swift 4.2

func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool {
    NSApplication.shared.terminate(self)
    return true
}
9
votes

Update for Swift 4.1:

func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool {
    NSApplication.shared.terminate(self)
    return true
}