> Widget 是 iOS14 的新特性,是一個桌面小插件,它的 UI 需要使用到 SwiftUI, 所以想要寫 Widget 首先需要學會寫 SwiftUI. 最終代碼 Github(https://github.com/wintelsui/iOS14Widget)
準備寫個包括三種樣式的簡單的 Widget
-
WidgetFamily中包含 3 中定義: systemSmall // A small widget. systemMedium //A medium-sized widget. systemLarge // A large widget 具體大小可以看蘋果的設計指南 https://developer.apple.com/design/human-interface-guidelines/ios/system-capabilities/widgets/
-
Widget 又有 2 中配置,靜態和動態,區別在於是否使用了Intent StaticConfiguration 和 IntentConfiguration. 如果需要"編輯小組件"中設置 Widget 參數,那麼就需要用到Intent.
隨意創建一個iOS項目(無關緊要,因爲我們只在乎 Widget), 然後創建Target 選擇 Widget Extension
因爲需要顯示 "編輯小組件" 中 配置參數,所以選擇 "Include Configuration Intent"
創建完成後,我們先來編輯一下TestWidget.intentdefinition文件, 這裏我將它自動生成的Configuration(改一個有辨識度的名字,改名字這一步不做也可以) 隨意的改成 TestWidgetConfiguration,去TestWidget.swift文件中將原有的ConfigurationIntent都替換爲TestWidgetConfigurationIntent, 並 build 一次(會自動生成TestWidgetConfigurationIntent.swift 類), 讓後在 Parameters 中添加兩個參數,並配置類型.
現在我們運行一下代碼,並在手機上把 Widget 添加到桌面, 長按Widget顯示菜單,選擇"編輯小組件",這時我們將看到我們的參數:
下面到了去寫代碼的時間了
模板生成了一些必要的代碼:
-
struct PlaceholderView : View {} 是臨時展示的視圖
-
struct TestWidgetEntryView : View {} 是 Widget 展示的主要視圖
-
struct SimpleEntry: TimelineEntry {} 是 Widget 的時間線中必要的對象
-
struct Provider: IntentTimelineProvider {} 控制着 Widget 的刷新,我們要提供一些用於刷新的內容,比如請求網絡數據後提交給時間線顯示數據.
/// 用於展示時候的快照(在插件中心選擇插件時候)
public func snapshot(for configuration: TestWidgetConfigurationIntent, with context: Context, completion: @escaping (SimpleEntry) -> ()) {}
/// 是真是的展示情況
public func timeline(for configuration: TestWidgetConfigurationIntent, with context: Context, completion: @escaping (Timeline<entry>) -> ()) {}
在這裏 timeline 這個方法的刷新規律,並不清楚,看WWDC視頻的時候,感覺難道是 30 分鐘左右嗎? 反正應用並不知道什麼時候會刷新(當然貌似可以從主程序中調用 WidgetCenter.shared.reloadAllTimelines() 強制刷新),但是不管怎樣,我們需要在timeline被調用時,提供數據用於展示.
開始編寫代碼 timeline(for configuration:....方法
public func timeline(for configuration: TestWidgetConfigurationIntent, with context: Context, completion: @escaping (Timeline<entry>) -> ()) {
// 讀取了設置中的參數, 實際上並不用,只是展示一下這個功能怎麼寫
let userName = configuration.userName ?? ""
let showFullName = configuration.showFullName?.boolValue ?? true
//此處並不着急completion(),可以發起網絡請求等
/*
let reqUrl = URL(string: "https://api.xygeng.cn/Bing")!
let task = URLSession.shared.dataTask(with: reqUrl) { (data, response, error) in
guard error == nil else {
let entryDate = Calendar.current.date(byAdding: .second, value: 20, to: Date())!
let entry = SimpleEntry(date: entryDate)
let timeline = Timeline(entries: [entry], policy: .after(entryDate))
completion(timeline)
return
}
let _ = getCommitInfo(fromData: data!)
let entryDate = Calendar.current.date(byAdding: .second, value: 20, to: Date())!
let entry = SimpleEntry(date: entryDate)
let timeline = Timeline(entries: [entry], policy: .after(entryDate))
completion(timeline)
}
task.resume()
*/
//本代碼 在 2 秒後刷新界面
let entryDate = Calendar.current.date(byAdding: .second, value: 2, to: Date())!
let entry = SimpleEntry(date: entryDate)
let timeline = Timeline(entries: [entry], policy: .after(entryDate))
completion(timeline)
}
視圖代碼,使用 @Environment(.widgetFamily) var family 來判斷當前是什麼大小樣式,其中PhotoView不多說了,是 Image 加了邊框.
struct TestWidgetEntryView : View {
var entry: Provider.Entry
@Environment(\.widgetFamily) var family
@ViewBuilder
var body: some View {
switch family {
case .systemSmall:
ZStack {
Color(red: 0.55, green: 0.73, blue: 1.0)
VStack(spacing: 10) {
PhotoView(imageName: "aragaki")
}
}
case .systemMedium:
ZStack {
Color(red:0.61, green:0.35, blue:0.71)
HStack(spacing: 10) {
PhotoView(imageName: "aragaki2")
Text("Aragaki")
.font(Font.system(size: 18))
.fontWeight(.heavy)
.shadow(color: Color.gray, radius: 5, x: 2, y: 2)
}
}
default:
ZStack {
Color(red:0.97, green:0.54, blue:0.88)
VStack {
HStack(spacing: 10) {
PhotoView(imageName: "aragaki3")
Text("Aragaki")
.font(Font.system(size: 18))
.fontWeight(.heavy)
.shadow(color: Color.gray, radius: 5, x: 2, y: 2)
}
Text("Aragaki")
.font(Font.system(size: 18))
.fontWeight(.heavy)
.shadow(color: Color.gray, radius: 5, x: 2, y: 2)
}
}
}
}
}
最終運行效果
最終代碼 Github(https://github.com/wintelsui/iOS14Widget)</entry></entry>