In my assets I have declared a theme color in two variants for both light and dark appearances, which works great. However, I have a specific place in the app where I need to use the light variant of the color regardless of whether dark mode is enabled or not. Is there any other way of getting that color in code, other than declaring the same color as a separate one with only a single variant?
In SwiftUI if there is need to use light variant for some subview it is enough to force specify .colorScheme
for it, like below
Color variants:
Demo:
var body: some View {
VStack {
Rectangle().fill(Color("testColor"))
.frame(width: 100, height: 100)
.environment(\.colorScheme, .light) // << force light
}
.frame(width: 300, height: 300)
.background(Color("testColor")) // << system appearance
}
If you're working with UIKit, then UIColor
's resolvedColor(with traitCollection:)
method is the way to go in order to override the default color scheme.
And if you, like me, don't like seeing UIColors hanging around in your SwiftUI code, below is a more SwiftUI-y way to get the same effect which worked pretty well for me so far:
extension View {
@ViewBuilder
func forceDarkVariant(_ forceDark: Bool) -> some View {
if forceDark {
self.environment(\.colorScheme, .dark)
} else {
self
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With