I have a color asset catalog in Xcode 13 that defines a set of colors in both light ("Any") and dark ("Dark") variants. For example:
I would like to programmatically enumerate the different colors, meaning, I'd like to get the color ( Color("hkMagenta")
) in both variants. Just getting it by name returns the "Any" variant.
How can I get the dark variant?
I had thought this would work:
ColorManager.hkMagenta.environment(\.colorScheme, .dark)
Unfortunately, no-go...
Cannot convert value of type 'some View' to expected element type 'Array<Color>.ArrayLiteralElement' (aka 'Color')
Any ideas?
You can specify.colorScheme for each view depending upon your needs like
import SwiftUI
struct ContentView: View {
var body: some View {
VStack(spacing: 20){
Text("Light Magenta color from asset")
.font(.headline)
.foregroundColor(Color("hkMagenta"))
.environment(\.colorScheme, .light) //ColoScheme
Text("Dark Magenta color from asset")
.font(.headline)
.foregroundColor(Color("hkMagenta"))
.environment(\.colorScheme, .dark) //ColoScheme
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
Thanks to @Asperi for pointing out https://stackoverflow.com/a/66950858/12299030 .
TL;DR is, you can get the light and dark variants using UIColor.resolvedColor()
like so:
let c = Color(UIColor(named: "hkMagenta").:resolvedColor(with: UITraitCollection(userInterfaceStyle. .dark)))
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.