简体   繁体   中英

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

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)

图像显示 AccentColor 资产被设置为粉红色

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: 在 ContentView 的窗口组中将色调设置为蓝色 还将其添加到 ContentView 本身

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM