SwiftUI 導航 API 參考指南
總覽
SwiftUI 的導航 API 提供了資料驅動、程式化的導航方式,可從簡單的堆疊擴展到複雜的多欄佈局。這項功能於 2022 年(iOS 16)伴隨 NavigationStack 和 NavigationSplitView 問世,在 2024 年(iOS 18)透過 Tab/Sidebar 的統一得到演進,並於 2025 年(iOS 26)藉由 Liquid Glass 設計獲得進一步優化。
演進時間軸
- 2022(iOS 16) NavigationStack、NavigationSplitView、NavigationPath、基於值的 NavigationLink
- 2024(iOS 18) Tab/Sidebar 統一、sidebarAdaptable 樣式、縮放導航過渡效果
- 2025(iOS 26) Liquid Glass 導航 chrome、底部對齊搜尋、浮動標籤欄、backgroundExtensionEffect
關鍵功能
- 資料驅動導航 NavigationPath 代表堆疊狀態,支援程式化的推入/彈出和深度連結
- 多欄佈局 NavigationSplitView 會自動適應(在 iPad 上為 3 欄,在 iPhone 上為單一堆疊)
- 狀態恢復 可編碼的 NavigationPath + SceneStorage,用於跨應用啟動的持久化
- Tab 整合 每個 Tab 的 NavigationStack 可在切換 Tab 時保存狀態(iOS 18+)
- Liquid Glass 自動的玻璃導航欄、側邊欄和工具欄(iOS 26+)
何時使用 vs UIKit
- SwiftUI 導航 新應用程式、多平台、較簡單的導航流程 → 使用 NavigationStack/SplitView
- UINavigationController 複雜的協調器模式、舊有程式碼、特定的 UIKit 功能 → 考慮使用 UIKit
相關技能
- 使用
axiom-swiftui-nav了解反模式、決策樹和壓力場景 - 使用
axiom-swiftui-nav-diag進行導航問題的系統性疑難排解
何時使用此技能
請在以下情況使用此技能:
- 實作導航 API NavigationStack、NavigationSplitView、NavigationPath、Tab+導航
- 深度連結或狀態恢復 URL 路由、可編碼的 NavigationPath、SceneStorage
- 採用 iOS 26+ 功能 Liquid Glass 導航、底部對齊搜尋、標籤欄最小化
- 選擇導航架構 堆疊 vs SplitView vs 協調器模式
API 演進
時間軸
| 年份 | iOS 版本 | 主要功能 |
|---|---|---|
| 2020 | iOS 14 | NavigationView(自 iOS 16 起已棄用) |
| 2022 | iOS 16 | NavigationStack, NavigationSplitView, NavigationPath, 基於值的 NavigationLink |
| 2024 | iOS 18 | Tab/Sidebar 統一, sidebarAdaptable, TabSection, 縮放過渡效果 |
| 2025 | iOS 26 | Liquid Glass 導航, backgroundExtensionEffect, tabBarMinimizeBehavior |
NavigationView(已棄用)
NavigationView 自 iOS 16 起已棄用。請在新程式碼中專一使用 NavigationStack(單欄推入/彈出)或 NavigationSplitView(多欄)。主要改進:單一的 NavigationPath 取代了每個連結的 isActive 綁定、基於值的型別安全性、內建的可編碼狀態恢復。請參閱「遷移至新的導航類型」文件。
NavigationStack 完整參考
NavigationStack 呈現如 iPhone 的「設定」或 macOS 的「系統設定」那樣的推入-彈出介面。
1.1 建立 NavigationStack
基本 NavigationStack
NavigationStack {
List(Category.allCases) { category in
NavigationLink(category.name, value: category)
}
.navigationTitle("分類")
.navigationDestination(for: Category.self) { category in
CategoryDetail(category: category)
}
}
帶路徑綁定(WWDC 2022, 6:05)
struct PushableStack: View {
@State private var path: [Recipe] = []
@StateObject private var dataModel = DataModel()
var body: some View {
NavigationStack(path: $path) {
List(Category.allCases) { category in
Section(category.localizedName) {
ForEach(dataModel.recipes(in: category)) { recipe in
NavigationLink(recipe.name, value: recipe)
}
}
}
.navigationTitle("分類")
.navigationDestination(for: Recipe.self) { recipe in
RecipeDetail(recipe: recipe)
}
}
.environmentObject(dataModel)
}
}
路徑綁定 + 呈現值的 NavigationLink + navigationDestination(for:) 形成了核心的資料驅動導航模式。
1.2 NavigationLink(基於值)
呈現值的 NavigationLink
// 正確:基於值(iOS 16+)
NavigationLink(recipe.name, value: recipe)
// 正確:使用自訂標籤
NavigationLink(value: recipe) {
RecipeTile(recipe: recipe)
}
// 已棄用:基於視圖(iOS 13-15)
NavigationLink(recipe.name) {
RecipeDetail(recipe: recipe) // 不要在新程式碼中使用
}
NavigationLink 如何與 NavigationStack 協作
- NavigationStack 維護一個
path集合 - 點擊一個呈現值的連結會將該值附加到路徑
- NavigationStack 將
navigationDestination修飾器映射到路徑值上 - 根據目的地映射,視圖會被推入堆疊
1.3 navigationDestination 修飾器
單一型別
.navigationDestination(for: Recipe.self) { recipe in
RecipeDetail(recipe: recipe)
}
多種型別
NavigationStack(path: $path) {
RootView()
.navigationDestination(for: Recipe.self) { recipe in
RecipeDetail(recipe: recipe)
}
.navigationDestination(for: Category.self) { category in
CategoryList(category: category)
}
.navigationDestination(for: Chef.self) { chef in
ChefProfile(chef: chef)
}
}
導航反模式
- 切勿在同一個 NavigationStack 階層中混合使用
navigationDestination(for:)和NavigationLink(destination:)— 會導致未定義行為 - 每種資料型別只註冊一次
navigationDestination(for:)— 重複會導致顯示錯誤的視圖
放置規則
- 將
navigationDestination放置在延遲容器之外(不要放在 ForEach 內部) - 為了程式碼組織,將其放置在相關的 NavigationLink 附近
- 必須在 NavigationStack 階層內部
// 正確:在延遲容器外部
ScrollView {
LazyVGrid(columns: columns) {
ForEach(recipes) { recipe in
NavigationLink(value: recipe) {
RecipeTile(recipe: recipe)
}
}
}
}
.navigationDestination(for: Recipe.self) { recipe in
RecipeDetail(recipe: recipe)
}
// 錯誤:放在 ForEach 內部(可能不會被載入)
ForEach(recipes) { recipe in
NavigationLink(value: recipe) { RecipeTile(recipe: recipe) }
.navigationDestination(for: Recipe.self) { r in // 不要這樣做
RecipeDetail(recipe: r)
}
}
1.4 NavigationPath
NavigationPath 是一個用於異質導航堆疊的型別抹除集合。
型別陣列 vs NavigationPath
// 型別陣列:所有值型別相同
@State private var path: [Recipe] = []
// NavigationPath:混合型別
@State private var path = NavigationPath()
NavigationPath 操作
// 附加值
path.append(recipe)
// 彈出到上一個
path.removeLast()
// 彈出到根
path.removeLast(path.count)
// 或
path = NavigationPath()
// 檢查數量
if path.count > 0 { ... }
// 深度連結:設定多個值
path.append(category)
path.append(recipe)
可編碼支援
// 當所有值都是 Codable 時,NavigationPath 是 Codable 的
@State private var path = NavigationPath()
// 編碼
let data = try JSONEncoder().encode(path.codable)
// 解碼
let codableRep = try JSONDecoder().decode(NavigationPath.CodableRepresentation.self, from: data)
path = NavigationPath(codableRep)
NavigationSplitView 完整參考
NavigationSplitView 建立能適應裝置尺寸的多欄佈局。
2.1 兩欄佈局
基本兩欄(WWDC 2022, 10:40)
struct MultipleColumns: View {
@State private var selectedCategory: Category?
@State private var selectedRecipe: Recipe?
@StateObject private var dataModel = DataModel()
var body: some View {
NavigationSplitView {
List(Category.allCases, selection: $selectedCategory) { category in
NavigationLink(category.localizedName, value: category)
}
.navigationTitle("分類")
} detail: {
if let recipe = selectedRecipe {
RecipeDetail(recipe: recipe)
} else {
Text("選擇一個食譜")
}
}
}
}
2.2 三欄佈局
在側邊欄和詳細欄之間添加一個 content: 閉包作為中間欄:
NavigationSplitView {
List(Category.allCases, selection: $selectedCategory) { category in
NavigationLink(category.localizedName, value: category)
}
} content: {
List(dataModel.recipes(in: selectedCategory), selection: $selectedRecipe) { recipe in
NavigationLink(recipe.name, value: recipe)
}
} detail: {
RecipeDetail(recipe: selectedRecipe)
}
2.3 NavigationSplitView 與 NavigationStack 結合
在詳細欄內部放置一個 NavigationStack(path:) 以實現從網格到詳細資訊的下鑽功能,同時保留側邊欄的選擇:
NavigationSplitView {
List(Category.allCases, selection: $selectedCategory) { ... }
} detail: {
NavigationStack(path: $path) {
RecipeGrid(category: selectedCategory)
.navigationDestination(for: Recipe.self) { recipe in
RecipeDetail(recipe: recipe)
}
}
}
2.4 欄位可見性
@State private var columnVisibility: NavigationSplitViewVisibility = .all
NavigationSplitView(columnVisibility: $columnVisibility) {
Sidebar()
} content: {
Content()
} detail: {
Detail()
}
// 程式化控制可見性
columnVisibility = .detailOnly // 隱藏側邊欄和內容欄
columnVisibility = .all // 顯示所有欄位
columnVisibility = .automatic // 由系統決定
2.5 自動適應
NavigationSplitView 會自動適應:
- iPad 橫向 所有欄位可見(取決於設定)
- iPad 直向/Slide Over 摺疊為覆蓋層或單欄
- iPhone 單一導航堆疊
- Apple Watch/TV 單一導航堆疊
在 iPhone 上,選擇的變更會自動轉換為推入/彈出。
2.6 iOS 26+ Liquid Glass 側邊欄(WWDC 2025, 323)
NavigationSplitView {
List { ... }
} detail: {
DetailView()
}
// 在 iPad/macOS 上,側邊欄會自動獲得 Liquid Glass 外觀
// 將內容延伸到玻璃側邊欄後面
.backgroundExtensionEffect() // 在安全區域外鏡像和模糊內容
深度連結和 URL 路由
3.1 深度連結模式
使用 .onOpenURL 接收 URL,用 URLComponents 解析,然後操作 NavigationPath:
.onOpenURL { url in
guard let components = URLComponents(url: url, resolvingAgainstBaseURL: false),
let host = components.host else { return }
path.removeLast(path.count) // 先彈出到根
// 解析 host/path 以確定目的地,然後 path.append(value)
}
對於多步驟深度連結(myapp://category/desserts/recipe/apple-pie),迭代 URL 路徑元件並附加每個解析的值以建構完整的導航堆疊。
有關全面的深度連結範例、錯誤診斷和測試流程,請參閱 axiom-swiftui-nav-diag(模式 3)。
狀態恢復
4.1 完整狀態恢復(WWDC 2022, 18:12)
struct UseSceneStorage: View {
@StateObject private var navModel = NavigationModel()
@SceneStorage("navigation") private var data: Data?
@StateObject private var dataModel = DataModel()
var body: some View {
NavigationSplitView {
List(Category.allCases, selection: $navModel.selectedCategory) { category in
NavigationLink(category.localizedName, value: category)
}
.navigationTitle("分類")
} detail: {
NavigationStack(path: $navModel.recipePath) {
RecipeGrid(category: navModel.selectedCategory)
}
}
.task {
// 在出現時恢復
if let data = data {
navModel.jsonData = data
}
// 在變更時儲存
for await _ in navModel.objectWillChangeSequence {
data = navModel.jsonData
}
}
.environmentObject(dataModel)
}
}
4.2 可編碼的 NavigationModel
class NavigationModel: ObservableObject, Codable {
@Published var selectedCategory: Category?
@Published var recipePath: [Recipe] = []
enum CodingKeys: String, CodingKey {
case selectedCategory
case recipePathIds // 儲存 ID,而非完整物件
}
func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encodeIfPresent(selectedCategory, forKey: .selectedCategory)
try container.encode(recipePath.map(\.id), forKey: .recipePathIds)
}
init() {}
required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
self.selectedCategory = try container.decodeIfPresent(Category.self, forKey: .selectedCategory)
let recipePathIds = try container.decode([Recipe.ID].self, forKey: .recipePathIds)
self.recipePath = recipePathIds.compactMap { DataModel.shared[$0] } // 忽略已刪除的項目
}
}
儲存 ID(而非完整的模型物件)並使用 compactMap 來優雅地處理已刪除的項目。如 4.1 所示,添加 jsonData 計算屬性和 objectWillChangeSequence 以整合 SceneStorage。
Tab + 導航整合
5.1 Tab 語法(iOS 18+)(WWDC 2024, 4:27)
TabView {
Tab("立即觀看", systemImage: "play") {
WatchNowView()
}
Tab("資料庫", systemImage: "books.vertical") {
LibraryView()
}
...
[為翻譯而截斷]