SwiftUI 導航
何時使用此技能
在以下情況使用:
- 選擇導航架構(NavigationStack vs NavigationSplitView vs TabView)
- 使用 NavigationPath 實作程式化導航
- 設定深度連結與 URL 路由
- 實作導航狀態還原
- 採用 Tab/Sidebar 模式(iOS 18+)
- 實作協調器/路由器模式
- 在發佈前請求導航實作的程式碼審查
相關技能
- 使用
axiom-swiftui-nav-diag進行導航失敗的系統性疑難排解 - 使用
axiom-swiftui-nav-ref查閱完整的 API 參考(包括 Tab 自訂、iOS 26+ 功能)及所有 WWDC 範例
範例提示
以下是開發者經常詢問且此技能旨在回答的真實問題:
1. "我應該為我的應用程式使用 NavigationStack 還是 NavigationSplitView?"
-> 此技能根據目標裝置、內容層級深度和多平台需求提供決策樹
2. "如何在 SwiftUI 中以程式方式導航?"
-> 此技能示範 NavigationPath 的操作模式,包括推入、彈出、彈出至根目錄以及深度連結
3. "我的深度連結無法運作。應用程式已開啟但顯示錯誤的畫面。"
-> 此技能涵蓋 URL 解析模式、路徑建構順序以及 onOpenURL 的時機問題
4. "當應用程式進入背景時,導航狀態會遺失。"
-> 此技能示範 Codable NavigationPath、SceneStorage 持久化以及抗崩潰的還原方法
5. "如何在 SwiftUI 中實作協調器模式?"
-> 此技能提供路由器模式的範例,並說明協調器何時能增加價值、何時只會增加複雜度
紅旗 — 應避免的反模式
如果你做了以下任何一件事,請立即停止並使用此技能中的模式:
❌ 關鍵 — 永遠不要這樣做
1. 在 iOS 16+ 使用已棄用的 NavigationView
// ❌ 錯誤 — 已棄用,在 iOS 16+ 行為不同
NavigationView {
List { ... }
}
.navigationViewStyle(.stack)
為什麼會失敗 NavigationView 自 iOS 16 起已棄用。它不支援 NavigationPath,導致程式化導航和深度連結不可靠。不同 iOS 版本的行為差異會引發錯誤。
2. 使用基於視圖的 NavigationLink 進行程式化導航
// ❌ 錯誤 — 無法以程式方式控制
NavigationLink("Recipe") {
RecipeDetail(recipe: recipe) // 視圖目的地,無值
}
為什麼會失敗 基於視圖的連結無法以程式方式控制。無法深度連結或彈出到此目的地。自 iOS 16 起已棄用。
3. 將 navigationDestination 放在惰性容器內部
// ❌ 錯誤 — 可能不會在需要時載入
LazyVGrid(columns: columns) {
ForEach(items) { item in
NavigationLink(value: item) { ... }
.navigationDestination(for: Item.self) { item in // 不要這樣做
ItemDetail(item: item)
}
}
}
為什麼會失敗 惰性容器不會立即載入所有視圖。navigationDestination 可能對 NavigationStack 不可見,導致導航靜默失敗。
4. 在 NavigationPath 中儲存完整的模型物件以進行還原
// ❌ 錯誤 — 重複資料,還原時資料過時
class NavigationModel: Codable {
var path: [Recipe] = [] // 完整的 Recipe 物件
}
為什麼會失敗 重複了模型中已有的資料。還原時,Recipe 資料可能已過時(在其他地方被編輯或刪除)。請使用 ID 並解析為當前資料。
5. 在 MainActor 外部修改 NavigationPath
// ❌ 錯誤 — 在非主執行緒更新 UI
Task.detached {
await viewModel.path.append(recipe) // 背景執行緒
}
為什麼會失敗 NavigationPath 與 UI 繫結。修改必須發生在 MainActor 上,否則導航狀態會損毀。可能導致崩潰或靜默失敗。
6. 缺少 @MainActor 隔離的導航狀態
// ❌ 錯誤 — 未隔離到 MainActor
class Router: ObservableObject {
@Published var path = NavigationPath() // 無 @MainActor
}
為什麼會失敗 在 Swift 6 嚴格的並行性檢查下,從 SwiftUI 視圖存取的 @Published 屬性需要 MainActor 隔離。會導致資料競爭警告和潛在的崩潰。
7. 在多分頁應用程式中未處理導航狀態
// ❌ 錯誤 — 跨分頁共用 NavigationPath
TabView {
Tab("Home") { HomeView() }
Tab("Settings") { SettingsView() }
}
// 所有分頁共用同一個 NavigationStack — 錯誤!
為什麼會失敗 每個分頁應有自己的 NavigationStack,以在切換分頁時保留導航狀態。共用狀態會造成令人困惑的使用者體驗。
8. 忽略 NavigationPath 解碼錯誤
// ❌ 錯誤 — 無效資料導致崩潰
let path = NavigationPath(try! decoder.decode(NavigationPath.CodableRepresentation.self, from: data))
為什麼會失敗 使用者可能已刪除路徑中的項目。Schema 可能已變更。強制解包會在還原時造成崩潰。
強制性第一步
在實作導航之前,務必完成這些步驟:
// 步驟 1:確定你的導航結構
// 詢問:單一堆疊?多欄?基於分頁且每個分頁自有導航?
// 在編寫任何程式碼之前記錄答案
// 步驟 2:根據結構選擇容器
// 單一堆疊(以 iPhone 為主):NavigationStack
// 多欄(以 iPad/Mac 為主):NavigationSplitView
// 基於分頁:TabView,每個分頁搭配 NavigationStack
// 步驟 3:定義導航的值類型
// 所有推入 NavigationStack 的值都必須是 Hashable
// 若需要深度連結/還原,也需遵循 Codable
struct Recipe: Hashable, Codable, Identifiable { ... }
// 步驟 4:規劃深度連結 URL(如果需要)
// myapp://recipe/{id}
// myapp://category/{name}/recipe/{id}
// 步驟 5:規劃狀態還原(如果需要)
// 你會使用 SceneStorage 嗎?哪些資料必須是 Codable?
快速決策樹
需要導航?
├─ 多欄介面(以 iPad/Mac 為主)?
│ └─ NavigationSplitView
│ ├─ 需要在詳細資訊欄中向下鑽取?
│ │ └─ 在詳細資訊欄內放入 NavigationStack(模式 3)
│ └─ 僅選擇即可的詳細資訊?
│ └─ 僅使用選擇繫結(模式 2)
├─ 基於分頁的應用程式?
│ └─ TabView
│ ├─ 每個分頁都需要向下鑽取?
│ │ └─ 每個分頁一個 NavigationStack(模式 4)
│ └─ 需要 iPad 側邊欄體驗?
│ └─ .tabViewStyle(.sidebarAdaptable)(模式 5)
└─ 單欄堆疊?
└─ NavigationStack
├─ 需要深度連結?
│ └─ 使用 NavigationPath(模式 1b)
└─ 簡單的推入/彈出?
└─ 型別陣列路徑(模式 1a)
需要狀態還原?
└─ SceneStorage + Codable NavigationPath(模式 6)
需要協調器抽象?
├─ 複雜的條件流程?
├─ 需要測試導航邏輯?
├─ 需要在許多畫面之間共用導航?
└─ 任一為「是」→ 路由器模式(模式 7)
全部為「否」→ 直接使用 NavigationPath
模式 1a:基本 NavigationStack
適用時機:簡單的推入/彈出導航,所有目的地類型相同
時間成本:5-10 分鐘
struct RecipeList: View {
@State private var path: [Recipe] = []
var body: some View {
NavigationStack(path: $path) {
List(recipes) { recipe in
NavigationLink(recipe.name, value: recipe)
}
.navigationTitle("Recipes")
.navigationDestination(for: Recipe.self) { recipe in
RecipeDetail(recipe: recipe)
}
}
}
// 程式化導航
func showRecipe(_ recipe: Recipe) {
path.append(recipe)
}
func popToRoot() {
path.removeAll()
}
}
關鍵點:
- 所有值類型相同時使用型別陣列
[Recipe] - 基於值的
NavigationLink(title, value:) navigationDestination(for:)放在惰性容器外部
模式 1b:NavigationStack 與深度連結
適用時機:多種目的地類型、基於 URL 的深度連結
時間成本:15-20 分鐘
struct ContentView: View {
@State private var path = NavigationPath()
var body: some View {
NavigationStack(path: $path) {
HomeView()
.navigationDestination(for: Category.self) { category in
CategoryView(category: category)
}
.navigationDestination(for: Recipe.self) { recipe in
RecipeDetail(recipe: recipe)
}
}
.onOpenURL { url in
handleDeepLink(url)
}
}
func handleDeepLink(_ url: URL) {
// URL: myapp://category/desserts/recipe/apple-pie
path.removeLast(path.count) // 先彈出到根目錄
guard let components = URLComponents(url: url, resolvingAgainstBaseURL: false) else { return }
let segments = components.path.split(separator: "/").map(String.init)
var index = 0
while index < segments.count - 1 {
switch segments[index] {
case "category":
if let category = Category(rawValue: segments[index + 1]) {
path.append(category)
}
index += 2
case "recipe":
if let recipe = dataModel.recipe(named: segments[index + 1]) {
path.append(recipe)
}
index += 2
default:
index += 1
}
}
}
}
關鍵點:
- 使用
NavigationPath處理異質類型 - 在建構深度連結路徑前先彈出到根目錄
- 以正確順序建構路徑(父層 → 子層)
模式 2:NavigationSplitView 基於選擇
適用時機:多欄佈局,詳細資訊欄顯示選取的項目
時間成本:10-15 分鐘
struct MultiColumnView: View {
@State private var selectedCategory: Category?
@State private var selectedRecipe: Recipe?
var body: some View {
NavigationSplitView {
List(Category.allCases, selection: $selectedCategory) { category in
NavigationLink(category.name, value: category)
}
.navigationTitle("Categories")
} content: {
if let category = selectedCategory {
List(recipes(in: category), selection: $selectedRecipe) { recipe in
NavigationLink(recipe.name, value: recipe)
}
.navigationTitle(category.name)
} else {
Text("Select a category")
}
} detail: {
if let recipe = selectedRecipe {
RecipeDetail(recipe: recipe)
} else {
Text("Select a recipe")
}
}
}
}
關鍵點:
- List 上的
selection: $binding會連接到欄位選擇 - 呈現值的連結會自動更新選擇
- 在 iPhone 上自動調整為單一堆疊
模式 3:NavigationSplitView 搭配詳細資訊欄中的堆疊
適用時機:多欄佈局,詳細資訊欄中需要向下鑽取功能
時間成本:20-25 分鐘
struct GridWithDrillDown: View {
@State private var selectedCategory: Category?
@State private var path: [Recipe] = []
var body: some View {
NavigationSplitView {
List(Category.allCases, selection: $selectedCategory) { category in
NavigationLink(category.name, value: category)
}
.navigationTitle("Categories")
} detail: {
NavigationStack(path: $path) {
if let category = selectedCategory {
RecipeGrid(category: category)
.navigationDestination(for: Recipe.self) { recipe in
RecipeDetail(recipe: recipe)
}
} else {
Text("Select a category")
}
}
}
}
}
關鍵點:
- NavigationStack 放在詳細資訊欄位內
- 從網格到詳細資訊的向下鑽取,同時保留側邊欄
- 向下鑽取使用獨立的路徑,側邊欄使用選擇
模式 4:TabView 搭配每個分頁的 NavigationStack
適用時機:基於分頁的應用程式,每個分頁有自己的導航
時間成本:15-20 分鐘
struct TabBasedApp: View {
var body: some View {
TabView {
Tab("Home", systemImage: "house") {
NavigationStack {
HomeView()
.navigationDestination(for: Item.self) { item in
ItemDetail(item: item)
}
}
}
Tab("Search", systemImage: "magnifyingglass") {
NavigationStack {
SearchView()
}
}
Tab("Settings", systemImage: "gear") {
NavigationStack {
SettingsView()
}
}
}
}
}
關鍵點:
- 每個 Tab 都有自己的 NavigationStack
- 切換分頁時保留導航狀態
- iOS 18+ 的 Tab 語法搭配 systemImage
模式 5:側邊欄可調整的 TabView(iOS 18+)
適用時機:在 iPhone 上顯示標籤列,在 iPad 上顯示側邊欄
時間成本:20-25 分鐘
struct AdaptableApp: View {
var body: some View {
TabView {
Tab("Watch Now", systemImage: "play") {
WatchNowView()
}
Tab("Library", systemImage: "books.vertical") {
LibraryView()
}
TabSection("Collections") {
Tab("Favorites", systemImage: "star") {
FavoritesView()
}
Tab("Recently Added", systemImage: "clock") {
RecentView()
}
}
Tab(role: .search) {
SearchView()
}
}
.tabViewStyle(.sidebarAdaptable)
}
}
關鍵點:
.tabViewStyle(.sidebarAdaptable)在 iPad 上啟用側邊欄TabSection在側邊欄中建立可折疊的群組Tab(role: .search)獲得特殊位置
模式 6:狀態還原
…
[已截斷以進行翻譯]