Swift4 Day99:iOS Widget

Alice
Daily Swift
Published in
8 min readJan 20, 2021

--

Meet WidgetKit — WWDC 2020 — Videos — Apple Developer

第一次看到 Widget 覺得真是太像 Android 了

為了支援各種 iOS 系統 widget只支援 SwiftUI ( iOS14 )

一開始提到 Widget 的三大目標:
Glanceable 一目瞭然的、Relevant 有意義的、Personalized 個人化的

Glanceable 一目瞭然、Relevant 相關的、Personalized 個人化的

Glanceable 一目瞭然

講者提到 Widget 不是 mini-app(相關實作 Session: Design great widgets),而是將重要資訊顯示在 Home screen。不需要按任何按鈕或花時間去了解複雜的 UI。

Relevant 有意義的

Personalized 個人化的

有三種尺寸,建議開發者能夠提供不同尺寸讓 User 有更多選擇,以天氣 weather app 為例,能夠點擊後選擇想看見的城市。

Widget 可以使用在 iOS、iPadOS 還有 macOS ,也可以完全用 Swift UI 來建立 Widget,並支援 Dynamic Type 與 Dark Mode。

Smart Stack

各種 widget 堆疊而成的 Smart Stack 可以手動切換,它們使用設備上的智能根據時間,位置和活動等因素在適當的時間顯示正確的小部件。

Siri建議小部件

Siri Recommendations小部件使用設備上的智能來顯示您根據使用模式可能採取的操作,例如點咖啡或開始播客。點按建議即可執行操作,而無需啟動應用程序。

Widget 有分兩種:StaticConfiguration、IntentConfiguration

像運動就是 StaticConfiguration 單純顯示資訊

Reminder 則是 IntentConfiguration 則可以顯示外

你可以點擊該提醒事項,讓用戶可以選擇。

Widget Place Holder UI

每個 Widget 的都要提供 Placeholder UI ,有以下三點要素:

1. 與實際上 App UI 相關的預設模式
2. 沒有 User 資料
3. 只有在環境改變時會使用(e.g. 修改 dynamic type )

為了方便開發者能夠通過 .isPlaceholder,直接呈現上述的 UI 設計

StatelessUI

  1. Widget 不是 mini app
  2. 不支援 scroll
  3. 不支援 Videos 與 animated images
  4. 僅提供 Tap interaction

以 Music 為例子,systemSmall 點擊一整個 Widget 可以用 deep link 直接導到 App 的歌曲頁面。systemMedium 則是可以點擊 album 到不同專輯。

Timeline

你可以使用固定的時間 Reload Widget ,在 timeline function 中做設定。或是在收到 Background notification 或 User 修改 app 資料時,讓系統強制更新 Widget UI。

Timeline 會 return 一個 entry 或是多個 entry

如何 reload 更多 entry 呢? TimelineReloadPolicy

有三種 atEnd、after、never

  1. 如果是 atEnd,當最後一個 entry 呈現之後,會開始排程 update 順序,當開始 update 時會觸發 timeline method 讓我們能拿到更多 entries。
  2. 如果是 after(10:00 PM),他就會在 10 點更新不管後面是否還有更多entries。
  3. 而 never 則是代表 widget 不會獨立更新畫面,除非我們利用 Widget Center API 明確的 reload 畫面

Widgets Code-along

主要基本UI、介紹 entry、snapshot、解釋: .atEnd, aftrer, never

介紹 family、placeholder、timeline設定、長按 widget 換資訊的功能、snapshot

實作 Link 點擊跳轉頁面功能、WidgetBundle、IntentHandler

開始實作,你可以在上述影片裡下載 demo 檔案 Building Widgets Using WidgetKit and SwiftUI ,蠻適合自己動手的。

或下載 https://github.com/wl02722691/Widget 開啟 Game Status Final ,跟 demo 的內容大致相同,加上一些影片中說明的中文註解。

Build SwiftUI views for widgets

用一個計算咖啡因的 app 從最基本的 Swift UI 教學如何做出 widgets 輕鬆實用教程。

--

--