Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I make a default button in macOS SwiftUI?

Tags:

macos

swiftui

I’ve build the following modal dialog in SwiftUI:

enter image description here

But I can’t figure out how to make the “Open” button be a default button (i.e. filled with blue in standard macOS HIG). The code for it looks like this:

struct
OpenLocationView : View
{
    @State private var location: String = ""

    var body: some View
    {
        VStack
        {
            HStack
            {
                Text("Location:")
                TextField("https://", text: $location) { self.openLocation() }
            }

            HStack
            {
                Spacer()
                Button("Cancel") { /* dismiss window */ }
                Button("Open") { self.openLocation() }
            }
        }
        .padding()
        .frame(minWidth: 500.0)
    }

    func
    openLocation()
    {
    }
}

I tried appending .buttonStyle(DefaultButtonStyle()), but that had no visible effect.

like image 369
Rick Avatar asked Oct 17 '25 17:10

Rick


2 Answers

On macOS 11, it is possible to define a keyboard shortcut using the keyboardShortcut view modifier.

The standard keyboard shortcuts .cancelAction (ESC key) and .defaultAction (Enter key) also apply a special coloration to the associated button.`

Button("Cancel") { ... }
    .keyboardShortcut(.cancelAction)
Button("Open") { ... }
    .keyboardShortcut(.defaultAction)
like image 99
Abdeslam MOKRANI Avatar answered Oct 20 '25 15:10

Abdeslam MOKRANI


Edit: April 2024, this is no longer an issue and the above will work as expected.

This is currently not possible in SwiftUI, see this question and workaround SwiftUI on Mac - How do I designate a button as being the primary?

like image 22
Theo Lampert Avatar answered Oct 20 '25 13:10

Theo Lampert