Coding01

Coding 点滴

0%

学习 iOS Widgets 开发之 Hello World

Introducing WidgetKit

Easily build widgets and make them available across iOS, iPadOS, and macOS using the WidgetKit framework and the new widget API for SwiftUI. Widgets now come in multiple sizes, and users can visit the new widget gallery to search, preview sizes, and place them anywhere on the Home screen to access important details at a glance. They can also add Smart Stacks — sets of widgets that use on-device intelligence to surface the right widget at the right moment, based on factors like time, location, and activity.

文字和图片来自 Introducing WidgetKit

在项目中 File->New->Target 添加 Target:

点击 Finsh 之后 Xcode 就会帮我们自动生成一个默认的 Widget:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
//
// Coding01Widgets.swift
// Coding01Widgets
//
// Created by 叶梅树 on 2020/11/1.
//

import WidgetKit
import SwiftUI
import Intents

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.
let currentDate = Date()
for hourOffset in 0 ..< 5 {
let entryDate = Calendar.current.date(byAdding: .hour, value: hourOffset, to: currentDate)!
let entry = SimpleEntry(date: entryDate, configuration: configuration)
entries.append(entry)
}

let timeline = Timeline(entries: entries, policy: .atEnd)
completion(timeline)
}
}

struct SimpleEntry: TimelineEntry {
let date: Date
let configuration: ConfigurationIntent
}

struct Coding01WidgetsEntryView : View {
var entry: Provider.Entry

var body: some View {
Text(entry.date, style: .time)
}
}

@main
struct Coding01Widgets: Widget {
let kind: String = "Coding01Widgets"

var body: some WidgetConfiguration {
IntentConfiguration(kind: kind, intent: ConfigurationIntent.self, provider: Provider()) { entry in
Coding01WidgetsEntryView(entry: entry)
}
.configurationDisplayName("My Widget")
.description("This is an example widget.")
}
}

struct Coding01Widgets_Previews: PreviewProvider {
static var previews: some View {
Coding01WidgetsEntryView(entry: SimpleEntry(date: Date(), configuration: ConfigurationIntent()))
.previewContext(WidgetPreviewContext(family: .systemSmall))
}
}

其中,

运行到真机设备上后就可以看到默认的时钟 Widget 了:

Welcome to my other publishing channels