[英]How to programmatically get asset catalog color variants from Xcode 13 in SwiftUI / Swift5.5?
I have a color asset catalog in Xcode 13 that defines a set of colors in both light ("Any") and dark ("Dark") variants.我在 Xcode 13 中有一个颜色资产目录,它定义了一组 colors 的浅色(“任何”)和深色(“深色”)变体。 For example:
例如:
I would like to programmatically enumerate the different colors, meaning, I'd like to get the color ( Color("hkMagenta")
) in both variants.我想以编程方式枚举不同的 colors,意思是,我想获得两种变体中的颜色(
Color("hkMagenta")
)。 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您可以根据需要为每个视图指定.colorScheme,例如
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 .感谢@Asperi 指出https://stackoverflow.com/a/66950858/12299030 。
TL;DR is, you can get the light and dark variants using UIColor.resolvedColor()
like so: TL;DR 是,您可以使用
UIColor.resolvedColor()
获得明暗变体,如下所示:
let c = Color(UIColor(named: "hkMagenta").:resolvedColor(with: UITraitCollection(userInterfaceStyle. .dark)))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.