Communitygithub.com

ComeOnOliver/skillshub

在實作導航模式、選擇 NavigationStack 或 NavigationSplitView、處理深度連結、採用協調器模式或請求導航實作程式碼審查時使用 – 防止 iOS 18+ 的導航狀態損毀、深度連結失敗及狀態還原錯誤。

skillshub 是什麼?

此技能為 SwiftUI 開發者提供了一套完整的導航實作指南,涵蓋從基本NavigationStack到複雜的NavigationSplitView與TabView模式。它協助開發者透過決策樹選擇最適合的導航容器,並提供模式化的程式碼範例,包括深度連結(URL routing)、狀態還原(SceneStorage與Codable NavigationPath)以及協調器模式(Router pattern)。此技能明確指出八種常見的反模式,例如在iOS 16+使用已棄用的NavigationView、在惰性容器內放置navigationDestination、或在非MainActor執行緒修改NavigationPath。它支援iOS 18+的新功能,如.sidebarAdaptable與TabSection,並適用於Claude Code、Cursor及Codex等AI代理工具。開發者可使用此技能進行導航架構審查、深度連結除錯及確保狀態還原的穩定性。

相容平台~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/ComeOnOliver/skillshub/tree/HEAD/skills/CharlesWiltgen/Axiom/axiom-swiftui-nav

在你喜歡的 AI 中提問

開啟一個已預先載入此 Agent Skill 的新對話。

說明文件

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:狀態還原

…

[已截斷以進行翻譯]

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

ComeOnOliver/skillshub

Create stunning, animation-rich HTML presentations from scratch or by converting PowerPoint files. Use when the user wants to build a presentation, convert a PPT/PPTX to web, or create slides for a talk/pitch. Helps non-designers discover their aesthetic through visual exploration rather than abstract choices.

ComeOnOliver/skillshub

Next.js 16+ 和 Turbopack — 增量打包、文件系统缓存、开发速度,以及何时使用 Turbopack 与 webpack。

ComeOnOliver/skillshub

SwiftUI architecture patterns, state management with @Observable, view composition, navigation, performance optimization, and modern iOS/macOS UI best practices.

ComeOnOliver/skillshub

See, Understand, Act on video and audio. See- ingest from local files, URLs, RTSP/live feeds, or live record desktop; return realtime context and playable stream links. Understand- extract frames, build visual/semantic/temporal indexes, and search moments with timestamps and auto-clips. Act- transcode and normalize (codec, fps, resolution, aspect ratio), perform timeline edits (subtitles, text/image overlays, branding, audio overlays, dubbing, translation), generate media assets (image, audio, video), and create real time alerts for events from live streams or desktop capture.

ComeOnOliver/skillshub

AI-assisted video editing workflows for cutting, structuring, and augmenting real footage. Covers the full pipeline from raw capture through FFmpeg, Remotion, ElevenLabs, fal.ai, and final polish in Descript or CapCut. Use when the user wants to edit video, cut footage, create vlogs, or build video content.

ComeOnOliver/skillshub

Next.js 15 애플리케이션을 위한 프론트엔드 개발 가이드라인. React 19, TypeScript, Shadcn/ui, Tailwind CSS를 사용한 모던 패턴. Server Components, Client Components, App Router, 파일 구조, Shadcn/ui 컴포넌트, 성능 최적화, TypeScript 모범 사례 포함. 컴포넌트, 페이지, 기능 생성, 데이터 페칭, 스타일링, 라우팅, 프론트엔드 코드 작업 시 사용.

ComeOnOliver/skillshub

Provides Tamagui patterns for config v4, compiler optimization, styled context, and cross-platform styling. Must use when working with Tamagui projects (tamagui.config.ts, @tamagui imports).

ComeOnOliver/skillshub

Create distinctive, production-grade frontend interfaces with high design quality. Use this skill when the user asks to build web components, pages, or applications. Generates creative, polished code that avoids generic AI aesthetics.

ComeOnOliver/skillshub

Create high-converting, visually distinctive landing pages. Use when building marketing pages, product launches, SaaS homepages, or any single-page conversion-focused website. Guides section-by-section composition with anti-AI-slop principles.

ComeOnOliver/skillshub

Auto-loaded context for Portfolio Buddy 2 development. Use for ANY task involving: React 19 development, TypeScript, portfolio analysis features, metrics calculations, trading strategy comparison, or working with the Portfolio Buddy 2 codebase. Contains tech stack, known issues, and architectural constraints.

ComeOnOliver/skillshub

Next.js development tooling via MCP. Inspect routes, components, build info, and debug Next.js apps. Use when working on Next.js applications, debugging routing, or inspecting app structure. NOT for general React or non-Next.js projects.

ComeOnOliver/skillshub

Implement UI using Shadcn MCP (atoms/theme) and 21st.dev MCP (complex sections). Use when adding buttons, layouts, or generating landing pages.

ComeOnOliver/skillshub

A conceptual skill for building an API client in Next.js that handles JWT tokens

ComeOnOliver/skillshub

Best practices and patterns for Next.js App Router, Server Actions, and Routing in this project.

ComeOnOliver/skillshub

The Design System, Theme, and UX rules for the Physical AI Hub.

ComeOnOliver/skillshub

Comprehensive frontend development skill for building modern, performant web applications using ReactJS, NextJS, TypeScript, Tailwind CSS. Includes component scaffolding, performance optimization, bundle analysis, and UI best practices. Use when developing frontend features, optimizing performance, implementing UI/UX designs, managing state, or reviewing frontend code.

ComeOnOliver/skillshub

This document captures learnings from fixing keyboard navigation issues when floating components (Select, DropdownMenu, Popover) have CSS open/close animations.

ComeOnOliver/skillshub

Build Next.js 16 applications with correct patterns and distinctive design. Use when creating pages, layouts, dynamic routes, upgrading from Next.js 15, or implementing proxy.ts. Covers breaking changes (async params/searchParams, Turbopack, cacheComponents) and frontend aesthetics. NOT when building non-React or backend-only applications.

ComeOnOliver/skillshub

Comprehensive Framer Motion animation library for React. Covers motion components, variants, gestures, page transitions, and scroll animations. Use when adding animations to React/Next.js applications.

ComeOnOliver/skillshub

Build interfaces that resonate, not just render. This skill enforces bold, intentional

相關技能