Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get light or dark variant of a color declared in assets

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?

like image 427
Arek Avatar asked Jan 01 '23 05:01

Arek


2 Answers

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:

colors

Demo:

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
}
like image 195
Asperi Avatar answered Jan 02 '23 19:01

Asperi


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
        }
    }
}
like image 44
Şafak Gezer Avatar answered Jan 02 '23 20:01

Şafak Gezer