In a View I can access the environment variables with the @Environment property wrapper like this:
struct MyView: View {
@Environment(\.colorScheme) var colorScheme: Color
var body: some View {
Text("Hello")
.foregroundColor(self.colorScheme == .light ? .black : .white)
}
}
In an extension, this is not possible, because I cannot put variables to an extension. How can I access the @Environment values in an extension, for example if I want to extend Color?
Until now I found out, that I can use Environment with the wrappedValue property like this:
extension Color {
static var darkModeText: Color {
if Environment(\.colorScheme).wrappedValue == .light {
return .black
} else {
return .white
}
}
}
The problem is, that this doesn't gets updated and always contains .light. I also tried using @Environment as a global variable, but this is (not yet) supported by property wrappers.