我使用以编程方式生成的 UIImage 构建我的小部件获取时间线.
所以我需要知道获取时间线如果 iOS 主题是浅色或深色。
我知道如何在 ViewController 中做到这一点traitCollection.userInterfaceStyle == .dark
,但是我怎样才能在小部件中做到这一点呢?
尽管 Widget 视图是静态的,但您仍然可能会检测到@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)
}
}
}
请注意,当系统配色方案更改时:
- 只有你的视图被重绘,
getTimeline
函数不再被调用
- 当系统配色方案更改时,默认颜色会自动更改
Here is a GitHub repository https://github.com/pawello2222/WidgetExamples#environment-widget with different Widget examples including the Environment Widget.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)