Skip to content

Instantly share code, notes, and snippets.

@mrnugget
Created July 1, 2023 11:05
Show Gist options
  • Save mrnugget/e4f983988bf3ad63f882d0d821c99990 to your computer and use it in GitHub Desktop.
Save mrnugget/e4f983988bf3ad63f882d0d821c99990 to your computer and use it in GitHub Desktop.
macOS Swift app with "Quit?" dialog that should accept return, but doesn't

The dialog doesn't accept "return" to quit the app.

import SwiftUI
struct ContentView: View {
@EnvironmentObject private var appDelegate: AppDelegate
var body: some View {
let confirmQuitting = Binding<Bool>(get: {
self.appDelegate.confirmQuit
}, set: {
self.appDelegate.confirmQuit = $0
})
VStack {
Text("Press Cmd+q to quit")
}
.padding()
.confirmationDialog(
"Quit?",
isPresented: confirmQuitting) {
Button("Quit", role: .destructive) {
NSLog("quitting")
NSApplication.shared.reply(toApplicationShouldTerminate: true)
}.keyboardShortcut(.defaultAction)
Button("Cancel", role: .cancel) {
NSLog("canceling")
NSApplication.shared.reply(toApplicationShouldTerminate: false)
}
.keyboardShortcut(.cancelAction)
} message: {
Text("This will quit the application.")
}.onSubmit {
NSApplication.shared.reply(toApplicationShouldTerminate: true)
}
}
}
import SwiftUI
@main
struct testingApp: App {
@NSApplicationDelegateAdaptor(AppDelegate.self) private var appDelegate
var body: some Scene {
WindowGroup {
ContentView()
}
}
}
class AppDelegate: NSObject, NSApplicationDelegate, ObservableObject {
@Published var confirmQuit: Bool = false
func applicationDidFinishLaunching(_ notification: Notification) {
NSLog("finished launching!!")
}
func applicationShouldTerminate(_ sender: NSApplication) -> NSApplication.TerminateReply {
confirmQuit = true
return .terminateLater
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment