小部件预览使用了错误大小的系列

Ada*_*don 11 ios widgetkit swiftui

我有一个如下所示的小部件视图:

struct WidgetEntryView: View {
    var entry: Provider.Entry

    @Environment(\.widgetFamily) var family
    
    var body: some View {
        switch family {
        case .systemSmall:
            ZStack {
                VStack(spacing: 12) {
                    // ...
                }
                .padding(10)
                .frame(maxWidth: .infinity, maxHeight: .infinity)
            }
            .background(Color.red.edgesIgnoringSafeArea(.all))
        case .systemMedium:
            ZStack {
                VStack(spacing: 12) {
                    // ...
                }
                .padding(10)
                .frame(maxWidth: .infinity, maxHeight: .infinity)
            }
            .background(Color.blue.edgesIgnoringSafeArea(.all))
        default:
            ZStack {
                VStack(spacing: 12) {
                    // ...
                    
                }
                .padding(10)
                .frame(maxWidth: .infinity, maxHeight: .infinity)
            }
            .background(Color.black.edgesIgnoringSafeArea(.all))
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

该小部件支持所有 3 个主要尺寸系列:

struct MyWidget: Widget {
    let kind: String = "MyWidget"
    
    var body: some WidgetConfiguration {
        IntentConfiguration(kind: kind, intent: ConfigurationIntent.self, provider: Provider()) { entry in
            WidgetEntryView(entry: entry)
        }
        .configurationDisplayName("MyWidget")
        .description("...")
        .supportedFamilies([.systemSmall, .systemMedium, .systemLarge])
    }
}
Run Code Online (Sandbox Code Playgroud)

这是我的 PreviewProvider:

struct Widget_Previews: PreviewProvider {
    static var previews: some View {
        Group {
            WidgetEntryView(entry: SimpleEntry(date: Date(), configuration: ConfigurationIntent())
                .previewContext(WidgetPreviewContext(family: .systemSmall))
            WidgetEntryView(entry: SimpleEntry(date: Date(), configuration: ConfigurationIntent())
                .previewContext(WidgetPreviewContext(family: .systemMedium))
            WidgetEntryView(entry: SimpleEntry(date: Date(), configuration: ConfigurationIntent())
                .previewContext(WidgetPreviewContext(family: .systemLarge))
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

因此,我在画布上预览了每个尺寸系列,但由于某种原因,所有尺寸系列都以蓝色背景渲染。或者换句话说,他们都被渲染成一个.systemMedium家庭。当我实际在模拟器上运行该小部件时,它具有正确的外观。为什么预览总是跳到案例.systemMedium而忽略其他案例​​?我怎样才能解决这个问题?

小智 2

不适@Environment var用于预览。但是你可以使用这样的环境修饰符:

YourWidgetView()
   .previewContext(WidgetPreviewContext(family: .systemSmall))
   .environment(\.widgetFamily, .systemSmall)
Run Code Online (Sandbox Code Playgroud)

但你必须编写一个EnvironmentKey扩展。这是我使用的解决方案: 如何设置 widgetFamily 环境