假如某组件需要大中小三种类型展示不同的view,可参照此文章进行设置
关键代码
@Environment(\.widgetFamily) var family
@ViewBuilder
var body: some View {
switch family {
case .systemSmall:
Text("小组件-中杯")
case .systemMedium:
Text("小组件-大杯")
case .systemLarge:
Text("小组件-特大杯")
default:
Text("小组件-默认给个中杯的")
}
}
import WidgetKit
import SwiftUI
import Intents
struct OneWordEntry: TimelineEntry {
let date: Date
let data: OneWord
}
struct OneWordProvider: IntentTimelineProvider {
func placeholder(in context: Context) -> OneWordEntry {
return OneWordEntry(date: Date(), data: OneWord(content: "人类的悲欢并不相通,我只觉得他们吵闹", length: 18))
}
func getSnapshot(for configuration: ConfigurationIntent, in context: Context, completion: @escaping (OneWordEntry) -> Void) {
let entry = OneWordEntry(date: Date(), data: OneWord(content: "一言", length: 2))
completion(entry)
}
func getTimeline(for configuration: ConfigurationIntent, in context: Context, completion: @escaping (Timeline<Entry>) -> Void) {
let currentDate = Date()
let refreshDate = Calendar.current.date(byAdding: .minute, value: 60, to: currentDate)!
OneWorldLoader.fetch { result in
let oneWord: OneWord
if case .success(let fetchedData) = result {
oneWord = fetchedData
} else {
oneWord = OneWord(content: "很遗憾本次更新失败,等待下一次更新.", length: 18)
}
let entry = OneWordEntry(date: currentDate,data: oneWord)
let timeline = Timeline(entries: [entry], policy: .after(refreshDate))
completion(timeline)
}
}
}
struct widgetEntryView : View {
var entry: OneWordProvider.Entry
@Environment(\.widgetFamily) var family
@ViewBuilder
var body: some View {
switch family {
case .systemSmall:
Text("小组件-中杯")
case .systemMedium:
Text("小组件-大杯")
case .systemLarge:
Text("小组件-特大杯")
default:
Text("小组件-默认给个中杯的")
}
}
}
@main
struct widget: Widget {
let kind: String = "widget"
var body: some WidgetConfiguration {
IntentConfiguration(kind: kind, intent: ConfigurationIntent.self, provider: OneWordProvider()) { entry in
widgetEntryView(entry: entry)
}
.configurationDisplayName("My Widget")
.description("This is an example widget.")
.supportedFamilies([.systemSmall,.systemMedium,
.systemLarge
])
}
}
网友评论