Created
December 22, 2021 01:23
-
-
Save maiyama18/73fb89086d790db07476d37b8a133687 to your computer and use it in GitHub Desktop.
This file contains 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 WidgetKit | |
import SwiftUI | |
struct RandomNumberWidgetProvider: TimelineProvider { | |
func placeholder(in context: Context) -> RandomNumberWidgetEntry { | |
RandomNumberWidgetEntry(date: Date(), number: 42) | |
} | |
func getSnapshot(in context: Context, completion: @escaping (RandomNumberWidgetEntry) -> ()) { | |
let entry = RandomNumberWidgetEntry(date: Date(), number: getRandomNumber()) | |
completion(entry) | |
} | |
func getTimeline(in context: Context, completion: @escaping (Timeline<RandomNumberWidgetEntry>) -> ()) { | |
var entries: [RandomNumberWidgetEntry] = [] | |
let currentDate = Date() | |
for hourOffset in 0 ..< 5 { | |
let entryDate = Calendar.current.date(byAdding: .hour, value: hourOffset, to: currentDate)! | |
let entry = RandomNumberWidgetEntry(date: entryDate, number: getRandomNumber()) | |
entries.append(entry) | |
} | |
let timeline = Timeline(entries: entries, policy: .atEnd) | |
completion(timeline) | |
} | |
private func getRandomNumber() -> Int { | |
Int.random(in: 1...100) | |
} | |
} | |
struct RandomNumberWidgetEntry: TimelineEntry { | |
let date: Date | |
let number: Int | |
} | |
struct RandomNumberWidgetEntryView : View { | |
var entry: RandomNumberWidgetProvider.Entry | |
var body: some View { | |
VStack { | |
Text("\(entry.number)") | |
.font(.largeTitle) | |
Text(entry.date, style: .time) | |
} | |
} | |
} | |
@main | |
struct Widgets: Widget { | |
let kind: String = "Widgets" | |
var body: some WidgetConfiguration { | |
StaticConfiguration(kind: kind, provider: RandomNumberWidgetProvider()) { entry in | |
RandomNumberWidgetEntryView(entry: entry) | |
} | |
.configurationDisplayName("Random Number Widget") | |
.description("This widget shows random number") | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment