The following is a code example from widget extension.
By using .environment(.colorScheme, ...), I am able to update view with correct theme aware named color.
However, I am not able to retrieve the correct RGB value, from the theme aware named color.
private func getColorScheme() -> ColorScheme {
if ... {
return ColorScheme.dark
} else {
return ColorScheme.light
}
}
@ViewBuilder
func contentView() -> some View {
// Light/ dark theme aware
let color = SwiftUI.Color("yellowNoteColor")
calculate(color)
HStack {
...
}
.background(color)
.environment(\.colorScheme, getColorScheme())
}
func calculate(_ color: SwiftUI.Color) {
var a: CGFloat = 0.0
var r: CGFloat = 0.0
var g: CGFloat = 0.0
var b: CGFloat = 0.0
let uiColor = UIColor(self)
uiColor.getRed(&r, green: &g, blue: &b, alpha: &a)
// !!! Always get the light theme color value !!!
}
Inside calculate
function, the retrieved value is always in the light theme color value.
My guess is, caculate
function is executed before .environment(\.colorScheme, getColorScheme())
, that's why we are getting light theme color value always.
May I know, how to get correct RGB value from theme aware named color?