How to close a sheet using button shortcuts

Viewed 41

I'm presenting a sheet to let the user enter a new message on a macOS app. I have a cancel and a save buttons, and I have assigned the .cancelAction and another shortcut to them. The idea is that if the user presses ESC, then the sheet closes without saving, and if the user presses CMD+Return then it will save it.

When the sheet is displaying, I can't get those button shortcuts to work.

The sheet code is as follow:

struct ComposeMessage: View {
    @Binding var showComposeMessage: Bool
    @State var text: String = ""
    @Environment(\.managedObjectContext) private var viewContext
    @Environment(\.presentationMode) var presentationMode
    
    var body: some View {
        VStack {
            HStack {
                TextEditor(text: $text).font(.body)
                    .disableAutocorrection(false)
                Spacer()
            }
            .padding()
            
            Divider()

            HStack {
                // cancel button
                Button {
                    presentationMode.wrappedValue.dismiss()
                } label: {
                    Image(systemName: "xmark.circle")
                }
                .help("Cancel")
                .buttonStyle(.plain)
                .keyboardShortcut(.cancelAction)
                
                Spacer()
                
                // save button                    
                Button {
                    if text == "" {return} // prevent saving empty message
                    print("Save message")
                    //showComposeMessage = false <- I tried using this too
                    presentationMode.wrappedValue.dismiss()
                } label: {
                    Image(systemName: "checkmark.circle")
                }
                .keyboardShortcut(.return, modifiers: [.command])
                .help("Save (⌘ Return)")
                .buttonStyle(.plain)
            }
            .font(.title2)
            .padding()
        }
        .frame(width: 400, height: 256)
    }
}

I'm calling it with:

sheet(isPresented: $showComposeMessage) {
          ComposeMessage(showComposeWindow: $showComposeWindow).background(Color(NSColor.textBackgroundColor))
}

If I use .popover instead, they do work. What am I missing?

Thanks for the help!

1 Answers

The answer is to use:

.buttonStyle(.borderless)
Related