有时候app需要提供多种widget供用户选择/使用,那么可以使用以下方法,不过需要注意,每个app最多可以包含5种小组件(Widget):
首先做几个小组件:
//省略之前的Provider和SimpleEntey部分
//第一个小组件
struct WidgetOne: Widget {let kind: String = "WidgetOne"var body: some WidgetConfiguration {IntentConfiguration(kind: kind, intent: ConfigurationIntent.self, provider: Provider()) { entry inWidgetOneEntryView(entry: entry)}.configurationDisplayName("My Widget").description("This is an example widget.").supportedFamilies([.systemSmall])}
}
struct WidgetOneEntryView : View {var entry: Provider.Entryvar body: some View {Text("one")}
}
//第二个小组件
struct WidgetTwoEntryView : View {var entry: Provider.Entryvar body: some View {Text("two")}
}
struct WidgetTwo: Widget {let kind: String = "WidgetTwo"var body: some WidgetConfiguration {IntentConfiguration(kind: kind, intent: ConfigurationIntent.self, provider: Provider()) { entry inWidgetTwoEntryView(entry: entry)}.configurationDisplayName("My Widget").description("This is an example widget.").supportedFamilies([.systemSmall])}
}
这里需要特别注意的是,要把原来struct WidgetOne: Widget
上面的@main
删掉,然后在输入以下代码:
@main
struct SwiftWidgetsBundle: WidgetBundle {@WidgetBundleBuildervar body: some Widget {WidgetOne()WidgetTwo()}
}
这时候就能看到这样的界面了: