Created
September 25, 2024 19:54
-
-
Save StewartLynch/1c70e385e63909c3d972c225d90c83ee to your computer and use it in GitHub Desktop.
Sample Widget Template Snippet
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 | |
// MARK: - Entry Data Model | |
struct <#WidgetName#>: TimelineEntry { | |
let date: Date | |
// Add any additional data you need for your widget | |
} | |
// MARK: - Entry Provider | |
struct <#WidgetName#>Provider: TimelineProvider { | |
func placeholder(in context: Context) -> <#WidgetName#> { | |
<#WidgetName#>(date: Date()) | |
} | |
func getSnapshot(in context: Context, completion: @escaping (<#WidgetName#>) -> Void) { | |
let entry = <#WidgetName#>(date: Date()) | |
completion(entry) | |
} | |
func getTimeline(in context: Context, completion: @escaping (Timeline<<#WidgetName#>>) -> Void) { | |
// Generate a timeline consisting of a single entry that refreshes after midnight | |
var entries: [<#WidgetName#>] = [] | |
// Create an entry for the current date | |
let currentDate = Date() | |
let entry = <#WidgetName#>(date: currentDate) | |
entries.append(entry) | |
// Schedule the next update for midnight | |
let calendar = Calendar.current | |
if let nextUpdateDate = calendar.nextDate(after: currentDate, matching: DateComponents(hour: 0), matchingPolicy: .strict) { | |
let timeline = Timeline(entries: entries, policy: .after(nextUpdateDate)) | |
completion(timeline) | |
} else { | |
// Fallback in case next update date couldn't be calculated | |
let timeline = Timeline(entries: entries, policy: .atEnd) | |
completion(timeline) | |
} | |
} | |
} | |
// MARK: - Widget View | |
struct <#WidgetName#>WidgetEntryView: View { | |
var entry: <#WidgetName#>Provider.Entry | |
var body: some View { | |
// Customize your widget's view here | |
Text("Today's date: \(entry.date, format: .dateTime)") | |
.padding() | |
} | |
} | |
// MARK: - Widget Definition | |
struct <#WidgetName#>Widget: Widget { | |
let kind: String = "<#WidgetName#>Widget" | |
var body: some WidgetConfiguration { | |
StaticConfiguration(kind: kind, provider: <#WidgetName#>Provider()) { entry in | |
<#WidgetName#>WidgetEntryView(entry: entry) | |
.containerBackground(.fill.tertiary, for: .widget) | |
} | |
.configurationDisplayName("Display Name Here") | |
.description("Widget Description here") | |
// Optionally specify supported families | |
.supportedFamilies([.systemSmall, .systemMedium, .systemLarge]) | |
} | |
} | |
#Preview(as: .systemMedium) { | |
<#WidgetName#>Widget() | |
} timeline: { | |
<#WidgetName#>(date: .now) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment