第一步创建 小组件
这里创建的名字 叫nytty,样板代码如下
这里对UI进行改造
并且将刷新时间改为1s
struct Provider: IntentTimelineProvider {
// 小组件的占位样式
func placeholder(in context: Context) -> SimpleEntry {
SimpleEntry(date: Date(), configuration: ConfigurationIntent())
}
//小组件的屏幕快照
func getSnapshot(for configuration: ConfigurationIntent, in context: Context, completion: @escaping (SimpleEntry) -> ()) {
let entry = SimpleEntry(date: Date(), configuration: configuration)
completion(entry)
}
//设置时间线,简单理解就是生成屏幕快照的时间规则
func getTimeline(for configuration: ConfigurationIntent, in context: Context, completion: @escaping (Timeline<Entry>) -> ()) {
var entries: [SimpleEntry] = []
// Generate a timeline consisting of five entries an hour apart, starting from the current date.
//以下代码以小时间隔生成4个时间点的快照,对应四个小时的时间
// 我们稍作修改,让他显示每一分钟的时间
let currentDate = Date()
for secondOffset in 0 ..< 60 {
let entryDate = Calendar.current.date(byAdding: .second, value: secondOffset, to: currentDate)!
let entry = SimpleEntry(date: entryDate, configuration: configuration)
entries.append(entry)
}
let timeline = Timeline(entries: entries, policy: .atEnd)
completion(timeline)
}
}
那么在我们的手机桌面这个时间就会 1s刷新一次
WidgetBundle 实现自定义多个小组件
/**
让小组件展示两种布局样式的组件
*/
@main
struct MyWidgetGroup: WidgetBundle{
@WidgetBundleBuilder
var body:some Widget{
TimerWidget1()
TimerWidget2()
}
}
struct TimerWidget1: Widget {
let kind: String = "eytty"
//从模拟器可以看出,三种尺寸的小组件都是这个样式
//那么如何让
var body: some WidgetConfiguration {
IntentConfiguration(kind: kind, intent: ConfigurationIntent.self, provider: TimeWidgetProvider()) { entry in
TimeWidgetEntryView(entry: entry)
}
//这里自定义选择面板的标题和介绍
.configurationDisplayName("NextSpace Widget")
.description("This is an flowus widget.")
//设置适配的小组件类型 .supportedFamilies([.systemSmall]) 这样就只有最小模式了
.supportedFamilies([.systemSmall])
}
}
struct TimerWidget2: Widget {
let kind: String = "eytty"
//从模拟器可以看出,三种尺寸的小组件都是这个样式
//那么如何让
var body: some WidgetConfiguration {
IntentConfiguration(kind: kind, intent: ConfigurationIntent.self, provider: TimeWidgetProvider()) { entry in
TimeWidgetEntryView(entry: entry)
}
//这里自定义选择面板的标题和介绍
.configurationDisplayName("Flowus Widget")
.description("This is an test widget.")
//设置适配的小组件类型 .supportedFamilies([.systemSmall]) 这样就只有最小模式了
.supportedFamilies([.systemMedium])
}
}