Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS 14 Widget Detect System Theme Change

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?

like image 535
Cosmin Avatar asked Aug 31 '25 20:08

Cosmin


1 Answers

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:

  • only your View is redrawn, the getTimeline function is not called again
  • the default colors change automatically when the system color scheme changes

Here is a GitHub repository with different Widget examples including the Environment Widget.

like image 111
pawello2222 Avatar answered Sep 03 '25 16:09

pawello2222