How to enable a user to close a dialog with the keyboard in SwiftUI on Mac Catalyst?

58 Views Asked by At

What is the idiomatic way for a user to close a dialog on Mac and to enable this in a SwiftUI Mac Catalyst App? I believe the idiomatic way is to press the escape key. I haven't been able to get this to work through a keyboardShortcut - please see my example. I am testing with XCode 15.0.1, MacOS 13.6, and iOS minimum deployment 16.0.

import SwiftUI

struct ContentView: View {
    @State private var isSheetPresented = false
    
    var body: some View {
        VStack {
            Button("Show Sheet") {
                isSheetPresented.toggle()
            }
            .sheet(isPresented: $isSheetPresented) {
                SheetView(dismissAction: {
                    isSheetPresented = false
                })
            }
        }
    }
}

struct SheetView: View {
    var dismissAction: () -> Void
    
    var body: some View {
        VStack {
            Text("Hello")
            
            Button("Dismiss") {
                dismissAction()
            }
        }
        .keyboardShortcut("e", modifiers: .command) // works
        .keyboardShortcut(.escape, modifiers: .command) // does not work
        .keyboardShortcut("e",modifiers: []) // does not work
        .keyboardShortcut(.escape, modifiers: []) // does not work
        .keyboardShortcut(.cancelAction)  // escape, command w and command period do not work
    }
}

@main
struct testkeyboardApp: App {
    var body: some Scene {
        WindowGroup {
            ContentView()
        }
    }
}
1

There are 1 best solutions below

0
John Cashew On

Both of these options work: .keyboardShortcut(.escape, modifiers: []) .keyboardShortcut(.cancelAction)

However, only the first keyboardShortcut modifier works.