外观更改时更新小部件 [英] Update Widget when appearance changes
本文介绍了外观更改时更新小部件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
当外观从 light
模式更改为 dark
模式,反之亦然时,我需要知道是否有人知道SwiftUI中的系统来更新Widget.
I would need to know if any of you know a system in SwiftUI to update a Widget when the appearance changes from light
mode to dark
mode and vice versa.
我可以更改文本和图像,但是我使用一种方法来显示地图的屏幕快照,因此每次外观更改时都应运行它以获取正确的地图颜色.
I can change text and images but I use a method to display a screenshot of a map and I should run it every time the appearance changes to get the correct map color.
推荐答案
- 创建两个屏幕截图(每个主题一个),并将其传递给条目:
struct SimpleEntry: TimelineEntry {
let date: Date
let mapScreenshots: [ColorScheme: Image]
}
struct Provider: TimelineProvider {
...
func getTimeline(in context: Context, completion: @escaping (Timeline<SimpleEntry>) -> Void) {
let entry = SimpleEntry(
date: Date(),
mapScreenshots: [
// replace with actual map screenshots
.dark: Image(systemName: "plus"),
.light: Image(systemName: "minus"),
]
)
let timeline = Timeline(entries: [entry], policy: .never)
completion(timeline)
}
}
- 使用
@Environment(\.colorScheme)
对主题更改做出反应:
- Use
@Environment(\.colorScheme)
to react to theme changes:
struct WidgetEntryView: View {
@Environment(\.colorScheme) var colorScheme
var entry: Provider.Entry
var body: some View {
if let screenshot = entry.mapScreenshots[colorScheme] {
screenshot
}
}
}
- iOS 14小部件检测系统主题更改
这篇关于外观更改时更新小部件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文