Home > other >  How to overwrite the accent color (within the code) in a macOS SwiftUI application?
How to overwrite the accent color (within the code) in a macOS SwiftUI application?

Time:04-29

I'm writing an application where I want there to be a default color and the user can then overwritten it with their own choice. This works in iOS but I realized the macOS version won't let me overwrite the accent color.

To demo this I created a mini project and set the asset to pink so it would be obvious what the accent color is (noticed if I don't do this it just stays default blue)

Image showing the AccentColor asset being set to pink

I then added a simple list to the main ContentView so I could see the accent color. My code is:

struct ContentView: View {
let myListitems = [
    "one", "two", "another", "and more"
]
@State var selectedItem:String?
var body: some View {
    VStack {
        Text("Hello, world!")
            .padding()
        List(myListitems, id: \.self, selection: $selectedItem) { item in
            Text(item)
        }
    }
}
}

I then tried to set the accent color to blue on the main WindowGroup part AND (separately) on the ContentView page. Neither affect the pink accent.

Images to show the code changes: Set tint to blue within the Window Group on ContentView Also added it to ContentView itself

Is there any way that you know of to overwrite this accent color (whether blue or user-defined in assets)? I would love the user to be able to change the color for the entire app but right now can't see how to even affect a view.

Thanks for any help

CodePudding user response:

Users can do that in system preferences by changing accent color and highlight color, multicolor means use the color defined by the apps, other colors mean use that in every app. You don't need to do anything, it works out of the box.

You can reference those colors by NSColor.controlAccentColor and NSColor.selectedContentBackgroundColor if you need them for custom UI elements. As far as I know, SwiftUI only has Color.accentColor out of the box but you can instantiate Color with an NSColor object.

  • Related