Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Close button event on OS X app swift 2.2

Tags:

macos

swift

cocoa

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)
like image 350
Ben Rockey Avatar asked Jan 12 '17 05:01

Ben Rockey


2 Answers

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
}
like image 169
Ben Rockey Avatar answered Oct 27 '22 20:10

Ben Rockey


Update for Swift 4.1:

func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool {
    NSApplication.shared.terminate(self)
    return true
}
like image 44
TDM Avatar answered Oct 27 '22 19:10

TDM