我有一个设置了.intentdefinition
文件的小部件,运行小部件时我可以从枚举中进行选择,但我不知道如何在代码中使用这些信息。
我想做的是根据用户在小部件设置中的选择,在getTimeline
中运行不同的代码。
如果有人能帮忙,我们将不胜感激。谢谢
要创建可配置小部件,需要使用IntentConfiguration
和IntentTimelineProvider
。这将允许您访问意向参数,稍后可以在getTimeline
函数中使用这些参数。
- 在Widget中,您需要使用
IntentConfiguration
(而不是StaticConfiguration
(并选择要使用的意图(intent
参数(:
struct IntentWidget: Widget {
let kind: String = "IntentWidget"
var body: some WidgetConfiguration {
IntentConfiguration(kind: kind, intent: CustomIntent.self, provider: Provider()) { entry in
WidgetEntryView(entry: entry)
}
.configurationDisplayName("Intent Widget")
.description("Intent Widget")
}
}
- 使您的提供商符合
IntentTimelineProvider
(而不是TimelineProvider
(。然后,您就可以在getSnapshot
和getTimeline
方法中使用您的意图:
struct Provider: IntentTimelineProvider {
func placeholder(in context: Context) -> SimpleEntry {
SimpleEntry(date: Date())
}
func getSnapshot(for configuration: CustomIntent, in context: Context, completion: @escaping (SimpleEntry) -> Void) {
completion(SimpleEntry(date: Date()))
}
func getTimeline(for configuration: CustomIntent, in context: Context, completion: @escaping (Timeline<Entry>) -> Void) {
// here you can access your intent configuration
// let selectedItem = configuration.selectedItem
...
completion(timeline)
}
}
有用的链接:
- 创建小部件扩展
- 制作可配置的小工具
这里是一个GitHub存储库,包含不同的Widget示例,包括Intent Widget