【问题标题】:Update Widget when appearance changes外观更改时更新小部件
【发布时间】:2020-10-31 15:08:55
【问题描述】:

我想知道你们中是否有人知道 SwiftUI 中的系统可以在外观从 light 模式更改为 dark 模式时更新小部件,反之亦然。

我可以更改文本和图像,但我使用一种方法来显示地图的屏幕截图,并且每次外观更改时我都应该运行它以获得正确的地图颜色。

【问题讨论】:

    标签: swift swiftui ios14 widgetkit


    【解决方案1】:
    1. 创建两个屏幕截图(每个主题一个)并将其传递到条目中:
    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)
        }
    }
    
    1. 使用@Environment(\.colorScheme) 对主题更改做出反应:
    struct WidgetEntryView: View {
        @Environment(\.colorScheme) var colorScheme
    
        var entry: Provider.Entry
    
        var body: some View {
            if let screenshot = entry.mapScreenshots[colorScheme] {
                screenshot
            }
        }
    }
    

    【讨论】:

    • 感谢@pawello2222 好主意,我没想到...只有一个问题:我使用MKMapSnapshotter 方法生成屏幕截图,但我无法定义地图外观。在文档中,我找到了一个实例属性“外观”,但它是一个 NSAppearance 属性,所以我不能在 iOS 中使用它......你有什么想法吗?
    • 让 traitCollectionLight = UITraitCollection.init(userInterfaceStyle: UIUserInterfaceStyle.light)
    • mapSnapshotOptions.traitCollection = traitCollectionLight
    猜你喜欢
    • 2012-12-17
    • 2013-12-21
    • 1970-01-01
    • 2015-01-10
    • 2013-05-05
    • 2018-01-28
    • 1970-01-01
    • 1970-01-01
    • 2021-04-26
    相关资源
    最近更新 更多