iOS 14小部件检测系统主题更改 [英] iOS 14 Widget Detect System Theme Change
问题描述
我在 getTimeline 中使用程序生成的UIImage构造了窗口小部件.
I construct my widget with a programmatically generated UIImage in getTimeline.
所以我需要在 getTimeline 中知道iOS主题是浅色还是深色.
So I need to know in getTimeline if the iOS theme is either Light or Dark.
我知道如何使用traitCollection.userInterfaceStyle == .dark
在ViewController中执行此操作,但是如何在Widget中执行此操作?
I know how to do that in a ViewController with traitCollection.userInterfaceStyle == .dark
, but how can I do it in a Widget?
推荐答案
尽管窗口小部件视图是静态的,但您仍然可以检测到@Environment(\.colorScheme)
.
Although Widget views are static, you may still detect @Environment(\.colorScheme)
.
这是一个简单的演示:
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
函数 - 当系统配色方案更改时,默认颜色会自动更改
这是一个 GitHub存储库,其中包含不同的小部件示例,包括环境小部件.
Here is a GitHub repository with different Widget examples including the Environment Widget.
这篇关于iOS 14小部件检测系统主题更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!