Communitygithub.com

ComeOnOliver/skillshub

參考資料 — 全面的 SwiftUI 導航 API 指南,涵蓋 NavigationStack (iOS 16+)、NavigationSplitView (iOS 16+)、NavigationPath、深度連結、狀態恢復、Tab+導航整合 (iOS 18+)、Liquid Glass 導航 (iOS 26+) 以及協調器模式。

skillshub 是什麼?

這是一份完整的 SwiftUI 導航 API 參考指南,專為使用 SwiftUI 構建應用程式的開發者設計。它詳細介紹了從 iOS 16 到 iOS 26 的核心導航技術,包括 NavigationStack、NavigationSplitView 和 NavigationPath,並提供了豐富的程式碼範例來說明如何實現資料驅動的導航、深度連結和狀態恢復。指南還涵蓋了 iOS 18 引入的 Tab/Sidebar 整合與 iOS 26 的 Liquid Glass 導航設計,幫助開發者為 iPhone、iPad 和 Mac 等多種平台建構適應性強的導航介面。此技能支援所有主要 AI 代理平台,作為關於 SwiftUI 導航最佳實踐和 API 使用方式的權威參考。

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

在你喜歡的 AI 中提問

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

說明文件

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 版本主要功能
2020iOS 14NavigationView(自 iOS 16 起已棄用)
2022iOS 16NavigationStack, NavigationSplitView, NavigationPath, 基於值的 NavigationLink
2024iOS 18Tab/Sidebar 統一, sidebarAdaptable, TabSection, 縮放過渡效果
2025iOS 26Liquid 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 協作

  1. NavigationStack 維護一個 path 集合
  2. 點擊一個呈現值的連結會將該值附加到路徑
  3. NavigationStack 將 navigationDestination 修飾器映射到路徑值上
  4. 根據目的地映射,視圖會被推入堆疊

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()
    }
...

[為翻譯而截斷]

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

相關技能