一般
適合日常確認,視覺表達安靜而克制。
快速接入
透過 Swift Package Manager 加入 ToastKit,接著將 ToastCenter 附加到需要顯示通知的檢視畫面。
import SwiftUI
import ToastKit
struct ContentView: View {
@State private var toasts = ToastCenter()
var body: some View {
Button("儲存") {
toasts.present(.normal, title: "更改已儲存")
}
.toasts(toasts)
}
}就這麼簡單。提示會顯示在安全區域底部,停留四秒。預設的滑動操作可刪除提示,也可暫存至下次開啟頁面時再顯示。
在 Xcode 中選擇 File → Add Package Dependencies,輸入 https://github.com/DavidRicardoWilde/swiftui-toastkit。
提示內容
ToastMessage 儲存提示文案、語意狀態、顯示時間,以及可選的點擊與滑動操作。簡單情境可使用便利方法;需要更多控制時,直接建立訊息物件。
toasts.present(.warning,
title: "儲存空間不足",
message: "請釋出空間以繼續同步。"
)
let message = ToastMessage(
status: .notification,
title: "新照片",
message: "今天新增 12 張照片",
icon: .system("photo.on.rectangle"),
duration: 6
)
toasts.present(message)適合日常確認,視覺表達安靜而克制。
提醒使用者注意尚未失敗的問題。
使用清楚、容易辨識的錯誤訊號。
通知狀態採用應用程式的強調色。
再次提交相同 id 的訊息會更新該提示並將它移到最前面,很適合呈現「正在同步…」接著變成「同步完成」這類進度狀態。
留一點時間
.automatic 使用中心的預設時間,預設為四秒。也可以直接指定秒數;需要使用者明確處理的訊息則可設為 .indefinite。
// 顯示兩秒
ToastMessage(title: "已複製", duration: 2)
// 直到使用者主動關閉
ToastMessage(title: "同步失敗", duration: .indefinite)
let toasts = ToastCenter(defaultDuration: 6)明確的下一步
使用者可以點擊、向任一方向滑動,或按住提示後先查看兩側操作再做決定。VoiceOver 也會依名稱提供相同操作。
| 手勢 | 預設行為 | 自訂方式 |
|---|---|---|
| 點擊 | 沒有操作,點擊會穿透至後方內容 | tapAction 或 onTap |
| 向 leading 側滑動 | 刪除提示 | swipeActions.leading |
| 向 trailing 側滑動 | 下次開啟時再次顯示 | swipeActions.trailing |
| 按住 | 預覽兩側滑動操作 | 重用相同的滑動操作 |
let archive = ToastAction(
id: "archive",
title: "封存",
icon: .system("archivebox"),
confirmation: "已封存"
) { toast in
store.archive(toast.id)
}
toasts.present(ToastMessage(
title: "來自 Ana 的訊息",
tapAction: ToastAction(title: "開啟") { toast in
router.open(toast.id)
},
swipeActions: ToastSwipeActions(leading: archive, trailing: .later)
))操作依序執行:先執行自身 handler,再通知堆疊的 onToastAction 觀察器,最後套用操作效果。內建 .later 會暫存提示,等頁面再次出現時恢復。
依需求自訂
預設的 .glass 樣式使用磨砂卡片,並依狀態調整顏色。可以透過 ToastTheme 修改設計令牌、選擇無裝飾的 .plain,或實作 ToastStyle 建立自己的卡片。
MyScreen()
.toasts(toasts)
.toastTheme(ToastTheme(
titleFont: .headline,
tint: { status in
status == .notification ? .pink : ToastTheme.standardTint(status)
},
cornerRadius: 16
))
// 從沒有背景與固定顏色的樣式開始
MyScreen().toasts(toasts).toastStyle(.plain)自訂樣式可以存取提示的圖示、標題、內文、狀態,以及卡片是否正處於長按軌道上。版面與手勢仍由堆疊負責。
恰當的位置
預設情況下,卡片從底部向上堆疊,寬度為可用安全區域的 60%。
// 頂部位置
MyScreen().toasts(toasts, placement: .top)
// 安全區域的 90%,或指定固定寬度
MyScreen().toasts(toasts, width: .fraction(0.9))
MyScreen().toasts(toasts, width: .points(320))在 TabView 中,將 .toasts(toasts) 附加到標籤頁內容上。系統標籤列與底部配件已計入安全區域。若有自訂浮動列,可標記為 .toastObstruction(),堆疊便會避開它。
為每個人打造
ToastKit 不要求特定手勢也能使用操作,並遵循 SwiftUI 環境中的輔助使用設定。
使用者的語言
ToastKit 內建操作標籤支援英文、日文、簡體中文與繁體中文。應用程式自己的文案由你管理:請為標題、內文及自訂操作標籤加入本地化。
// 將應用程式文案放在 String Catalog 或 Localizable.strings。
toasts.present(.warning,
title: String(localized: "storage.low.title"),
message: String(localized: "storage.low.message")
)ToastKit 會依照宿主應用程式的語言環境顯示內建標籤。自訂 ToastAction 標題與確認文案是一般字串,可使用應用程式現有的本地化工具處理。