I construct my widget with a programmatically generated UIImage in getTimeline.
So I need to know in getTimeline if the iOS theme is either Light or Dark.
I know how to do that in a ViewController with traitCollection.userInterfaceStyle == .dark
, but how can I do it in a Widget?
Although Widget views are static, you may still detect @Environment(\.colorScheme)
.
Here is a simple demo:
struct WidgetEntryView: View {
@Environment(\.colorScheme) var colorScheme
var entry: Provider.Entry
var bgColor: some View {
colorScheme == .dark ? Color.red : Color.orange
}
var body: some View {
ZStack {
bgColor
Text(entry.date, style: .time)
}
}
}
Note that when the system color scheme changes:
getTimeline
function is not called againHere is a GitHub repository with different Widget examples including the Environment Widget.
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