Reputation: 147
How do I create a local variable with specifically the dark mode color in SwiftUI. I am trying to avoid specifying the color scheme of each view to be dark to get the dark mode color.
For example in UIKit, I can get the dark mode color with this code
let traitCollection = UITraitCollection(userInterfaceStyle: .dark)
let darkModeBlueUIColor = UIColor.systemBlue.resolvedColor(with: traitCollection)
I know I can convert from a UIColor, but I want to specify it only using SwiftUI so it works on all platforms.
let darkModeBlueSwiftuiColor = Color(darkModeBlueUIColor)
I would like to do something like this involving a helper function
let darkModeBlueColor = Color.blue.darkModeColor
Upvotes: 10
Views: 4100
Reputation: 116
A little late but I also ran into this problem. My extension is based on Mani's solution but directly uses SwiftUI Color instead of UIColor:
extension Color {
var light: Self {
var environment = EnvironmentValues()
environment.colorScheme = .light
return Color(resolve(in: environment))
}
var dark: Self {
var environment = EnvironmentValues()
environment.colorScheme = .dark
return Color(resolve(in: environment))
}
}
And is used like so:
Color.primary.light
Upvotes: 4
Reputation: 1635
If anyone drops by this question, heres a solution that I've found and use:
extension UIColor {
var light: UIColor {
resolvedColor(with: .init(userInterfaceStyle: .light))
}
var dark: UIColor {
resolvedColor(with: .init(userInterfaceStyle: .dark))
}
}
I found it here.
You can initialize a SwiftUI Color
this way:
if let primary = UIColor(named: "primary") {
let dark = Color(primary.dark)
let light = Color(primary.light)
}
Upvotes: 2
Reputation: 257533
To draw color for specific color schema just use it in view body as
Color("testColor")
.colorScheme(.dark) // << this !!
also if you use color variable then same can be done.
Upvotes: 4