Communitygithub.com

ComeOnOliver/skillshub

参考资料——全面的 SwiftUI 导航指南,涵盖 NavigationStack(iOS 16+)、NavigationSplitView(iOS 16+)、NavigationPath、深度链接、状态恢复、Tab+导航集成(iOS 18+)、Liquid Glass 导航(iOS 26+)以及协调器模式。

skillshub 是什么?

该技能是 SwiftUI 导航 API 的完整参考指南,面向 iOS 16 至 iOS 26 的开发者。它系统性地介绍了 NavigationStack(单列推/弹导航)和 NavigationSplitView(多列自适应布局),以及它们的数据驱动编程模型,包括 NavigationPath 支持的类型擦除异构堆栈。技能深入解释了如何使用值驱动的 NavigationLink 和 `navigationDestination(for:)` 修饰符,并附有大量代码示例,展示了正确的放置规则和常见反模式。此外,它还涵盖了深度链接(使用 `onOpenURL` 和 URLComponents)和状态恢复(结合 Codable NavigationPath 与 SceneStorage)的集成模式。针对 iOS 18+,技能展示了 Tab + NavigationStack 集成,实现每个标签页的状态保持。对于 iOS 26+,它引入了 Liquid Glass 导航铬、底部对齐搜索和浮动标签栏等新功能。总之,该技能是构建从简单列表到多列自适应界面的任何 SwiftUI 导航架构的实用参考,并帮助开发者避免反模式,采用数据驱动的导航方式。

兼容平台~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 提供了数据驱动的编程式导航,可以从小型堆栈扩展到复杂的多列布局。于 iOS 16(2022 年)引入 NavigationStack 和 NavigationSplitView,在 iOS 18(2024 年)通过 Tab/侧边栏统一发展,并在 iOS 26(2025 年)通过 Liquid Glass 设计进行了完善。

发展时间线

  • 2022 (iOS 16) NavigationStack, NavigationSplitView, NavigationPath, 基于值的 NavigationLink
  • 2024 (iOS 18) Tab/侧边栏统一, sidebarAdaptable 样式, 缩放导航过渡
  • 2025 (iOS 26) Liquid Glass 导航铬, 底部对齐搜索, 浮动标签栏, backgroundExtensionEffect

关键能力

  • 数据驱动导航 NavigationPath 表示堆栈状态,支持编程式推入/弹出和深度链接
  • 多列布局 NavigationSplitView 自动适配(iPad 上 3 列 → iPhone 上单堆栈)
  • 状态恢复 Codable NavigationPath + SceneStorage 实现在应用启动间持久化
  • 标签集成 每个标签页的 NavigationStack,切换标签时保持状态(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 路由, Codable NavigationPath, SceneStorage
  • 采用 iOS 26+ 功能 Liquid Glass 导航, 底部对齐搜索, 标签栏最小化
  • 选择导航架构 堆栈 vs 分栏视图 vs 协调器模式

API 演变

时间线

年份iOS 版本关键功能
2020iOS 14NavigationView(已在 iOS 16 中弃用)
2022iOS 16NavigationStack, NavigationSplitView, NavigationPath, 基于值的 NavigationLink
2024iOS 18Tab/侧边栏统一, sidebarAdaptable, TabSection, 缩放过渡
2025iOS 26Liquid Glass 导航, backgroundExtensionEffect, tabBarMinimizeBehavior

NavigationView(已弃用)

NavigationView 自 iOS 16 起已弃用。在新代码中应完全使用 NavigationStack(单列推/弹)或 NavigationSplitView(多列)。主要改进:单个 NavigationPath 替代了每个链接的 isActive 绑定,基于值的类型安全性,内置 Codable 状态恢复。请参阅“迁移到新的导航类型”文档。


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. 点击值呈现的链接会将值附加到 path 上
  3. NavigationStack 将 navigationDestination 修饰符映射到 path 值上
  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 支持

// 当所有值都是 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 Codable NavigationModel

class NavigationModel: ObservableObject, Codable {
    @Published var selectedCategory: Category?
    @Published var recipePath: [Recipe] = []

    enum CodingKeys: String, CodingKey {
        case selectedCategory
        case recipePathIds  // 存储 IDs,而不是完整对象
    }

    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] } // 丢弃已删除的项目
    }
}

存储 IDs(而非完整的模型对象)并使用 compactMap 来优雅处理已删除的项目。添加 jsonData 计算属性和 objectWillChangeSequence 以便与 SceneStorage 集成,如 4.1 所示。


Tab + 导航集成

5.1 Tab 语法(iOS 18+)(WWDC 2024, 4:27)

TabView {
    Tab("立即观看", systemImage: "play") {
        WatchNowView()
    }
    Tab("资料库", systemImage: "books.vertical") {
        LibraryView()
    }
    Tab("搜索", systemImage: "magnifyingglass") {
        SearchView()
    }
}

每个标签页维护独立的 NavigationStack:

struct TabbedNavigation: View {
    @State private var selectedTab = TabIdentifier.watchNow
    @State private var watchPath: [WatchDestination] = []
    @State private var libraryPath: [LibraryDestination] = []
    @State private var searchPath: [SearchDestination] = []

    var body: some View {
        TabView(selection: $selectedTab) {
            NavigationStack(path: $watchPath) {
                WatchNowView()
            }
            .tabItem { Label("立即观看", systemImage: "play") }
            .tag(TabIdentifier.watchNow)

            NavigationStack(path: $libraryPath) {
                LibraryView()
            }
            .tabItem { Label("资料库", systemImage: "books.vertical") }
            .tag(TabIdentifier.library)

            NavigationStack(path: $searchPath) {
                SearchView()
            }
            .tabItem { Label("搜索", systemImage: "magnifyingglass") }
            .tag(TabIdentifier.search)
        }
    }
}

Tab 键(iOS 18+)提供声明式标签定制,包括徽章、上下文菜单和自定义内容。

5.2 标签栏最小化(iOS 26+)

在 iOS 26 中,标签栏可以最小化为浮动药丸:

// 在 iOS 26+ 上默认启用
// 通过向上滑动或系统提示进入最小化模式
// 形状:原始的浮动药丸

iOS 26+ Liquid Glass 导航

6.1 Liquid Glass 功能

导航栏、侧边栏和工具栏自动获得 Liquid Glass 外观。当内容滚动到它们后面时,会应用实时模糊和着色:

NavigationStack {
    ScrollView {
        // 内容滚动到导航栏后面
        // 导航栏自动变得玻璃般透明
    }
    .navigationTitle("食谱")
}

关键属性:

  • 自动玻璃材质,带实时背景模糊
  • 水平刻度背景延伸(backgroundExtensionEffect)
  • 底部对齐搜索栏
  • 增强的动画和过渡

6.2 backgroundExtensionEffect

在玻璃导航要素后面延伸和模糊内容:

ScrollView {
    ColorfulContent()
}
.backgroundExtensionEffect()
// 内容在侧边栏/导航栏后面微妙地模糊
// 创建深度和连续性的幻觉

协调器模式参考

协调器模式对于 SwiftUI 导航来说通常不是必需的。在使用 UIKit 协调器之前,请考虑 NavigationStack + NavigationPath + navigationDestination。仅当您需要 UIKit 特定功能(如自定义过渡或交互式弹出手势)时才使用协调器。

7.1 何时考虑协调器模式

  • 需要 UIKit 特定的导航行为(例如,自定义交互式弹出)
  • 与现有的 UIKit 导航控制器集成
  • 具有复杂回调和状态管理的全局导航逻辑
  • 多窗口或多场景协调

7.2 示例:SwiftUI 协调器

class AppCoordinator: ObservableObject {
    @Published var path: [Route] = []

    func navigate(to route: Route) {
        path.append(route)
    }

    func popToRoot() {
        path.removeAll()
    }

    func handleDeepLink(_ url: URL) {
        // 解析 URL 并构建路径
    }
}

struct AppView: View {
    @StateObject private var coordinator = AppCoordinator()

    var body: some View {
        NavigationStack(path: $coordinator.path) {
            RootView()
                .navigationDestination(for: Route.self) { route in
                    switch route {
                    case .detail(let id):
                        DetailView(id: id)
                    case .settings:
                        SettingsView()
                    }
                }
        }
        .environmentObject(coordinator)
    }
}

最佳实践总结

✅ 做

  • 新导航使用 NavigationStack + NavigationSplitView
  • 使用基于值的 NavigationLink + navigationDestination
  • 每种数据类型只注册一次 navigationDestination
  • 将 navigationDestination 放在惰性容器外部
  • 对异构堆栈使用 NavigationPath
  • 对持久化路径使用 Codable NavigationPath
  • 每个标签页维护独立的 NavigationStack(iOS 18+)
  • 在 iOS 26+ 上采用 Liquid Glass 等同名家

❌ 不要

  • 不要在新的 iOS 16+ 代码中使用 NavigationView
  • 不要混合使用基于值的 NavigationLink 和基于目的地 的 NavigationLink
  • 不要在 ForEach 或 LazyVStack 内部使用 navigationDestination
  • 不要对同一类型重复使用 navigationDestination
  • 不要存储完整模型对象以进行状态恢复 —— 使用 IDs
  • 除非必要,不要使用协调器模式 —— 使用 NavigationPath
  • 不要忽略 iOS 18 的 Tab 语法 —— 它提供了更好的标签定制

支持的平台

  • iOS 16+, iPadOS 16+, macOS 13+, tvOS 16+, watchOS 9+, visionOS 1+
  • Liquid Glass 功能需要 iOS 26+, iPadOS 26+, macOS 15+
  • Tab 键语法需要 iOS 18+, iPadOS 18+, macOS 15+

参考

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

相关技能