macosswiftuiaccent-color

Create colored MacOS button with SwiftUI with the same style as in built-in apps


I have to create a MacOS app with SwiftUI that must look like a built-in app, conforming to all appearance settings.

I need to create accent colored buttons that look like the "Done" button here (Safari - Settings - Search - Manage Websites...) Safari Settings Search Manage ...

The best I could get in my app looks like this:

My app #2

The code I have:

Button (action: {
}, label: {
    Text("Next")
        .padding(EdgeInsets (top: 5, leading: 12, bottom: 7, trailing: 12))
})
.buttonStyle(PlainButtonStyle())
.foregroundStyle(.white)
.background(Color.accentColor, in: RoundedRectangle(cornerRadius: 5.0))

/*EDIT: Result with suggestion in comments

Button (action: {
}, label: {
    Text("Next")
        .padding(EdgeInsets (top: 5, leading: 12, bottom: 7, trailing: 12))
        .foregroundStyle(.white)
})
.buttonStyle(.borderedProminent)

My app #3 */

Is there a builtin style or modifier I am missing?

Thanks for any tips!


Solution

  • That is a .bordered button with the .defaultAction keyboard shortcut. That is, it can be triggered by pressing the return key.

    Relevant quote from the documentation:

    On macOS, the default button is designated with special coloration. If more than one control is assigned this shortcut, only the first one is emphasized.

    Here is some example code that produces such a button:

    struct ContentView: View {
        var body: some View {
            Button {
                
            } label: {
                Text("Done")
            }
            .buttonStyle(.bordered)
            .keyboardShortcut(.defaultAction)
        }
    }
    

    With the system accent color set to yellow, it looks like this:

    enter image description here