Created
June 30, 2023 22:36
-
-
Save ketzusaka/03371143de70347c2a87af047e1cf918 to your computer and use it in GitHub Desktop.
widget example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import SwiftUI | |
| import WidgetKit | |
| struct Mode1: Codable { | |
| var foo: String | |
| } | |
| struct Mode2: Codable { | |
| var bar: String | |
| } | |
| struct SimpleEntry: TimelineEntry { | |
| enum Mode { | |
| case mode1(Mode1) | |
| case mode2(Mode2) | |
| } | |
| var date: Date | |
| var mode: Mode | |
| } | |
| struct Provider: TimelineProvider { | |
| func placeholder(in context: Context) -> SimpleEntry { | |
| SimpleEntry(date: .now, mode: .mode1(Mode1(foo: "hey"))) | |
| } | |
| func getSnapshot(in context: Context, completion: @escaping (SimpleEntry) -> ()) { | |
| completion(Entry(date: .now, mode: .mode2(Mode2(bar: "yo")))) | |
| } | |
| func getTimeline(in context: Context, completion: @escaping (Timeline<SimpleEntry>) -> ()) { | |
| var entries = [SimpleEntry]() | |
| // Here you should pull read the user's configuration to determine which "Mode" you should be using for each entry | |
| // I'm going to populate an entry for each mode as an example. | |
| let currentDate = Date() | |
| entries.append(SimpleEntry(date: currentDate, mode: .mode1(Mode1(foo: "Hello")))) | |
| entries.append(SimpleEntry(date: currentDate, mode: .mode2(Mode2(bar: "こんにちは")))) | |
| let timeline = Timeline(entries: entries, policy: .atEnd) | |
| completion(timeline) | |
| } | |
| } | |
| struct SampleWidgetEntryView : View { | |
| var entry: Provider.Entry | |
| var body: some View { | |
| switch entry.mode { | |
| case .mode1(let modeConfiguration): | |
| Text(modeConfiguration.foo) | |
| case .mode2(let modeConfiguration): | |
| Text(modeConfiguration.bar) | |
| } | |
| } | |
| } | |
| struct SampleWidget: Widget { | |
| let kind: String = "SampleWidget" | |
| var body: some WidgetConfiguration { | |
| StaticConfiguration(kind: kind, provider: Provider()) { entry in | |
| SampleWidgetEntryView(entry: entry) | |
| } | |
| .configurationDisplayName("My Widget") | |
| .description("This is an example widget.") | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment