Communitygithub.com

SwiftUI 导航

用于实现导航模式,选择 NavigationStack 与 NavigationSplitView、处理深层链接、采用协调器模式或请求导航实现代码审查时使用——防止 iOS 18+ 的导航状态损坏、深层链接失败和状态恢复错误。

SwiftUI 导航 是什么?

该技能为 SwiftUI 开发者提供了在 iOS 18+ 应用中实现可靠、可维护导航架构的全面指南。它帮助决定合适的导航容器(NavigationStack、NavigationSplitView、TabView),处理程序化导航(包括使用 NavigationPath 处理多种数据类型),并实现深层链接与 URL 路由。该技能详细强调了常见反模式,例如使用已弃用的 NavigationView、在惰性容器中放置 navigationDestination、以及忽略 MainActor 隔离或 NavigationPath 解码错误。它支持所有主要平台(iOS、iPadOS、macOS),并包含带有代码示例的实用模式,用于基本堆栈导航、多列布局、基于标签的导航以及通过 SceneStorage 和 Codable NavigationPath 进行状态恢复。此外,它还提供了决策树和关于采用协调器/路由器模式的建议,帮助开发者在架构做出更明智的决定。

兼容平台~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 路由
  • 为导航实现状态恢复
  • 采用标签/侧边栏模式(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. "当应用进入后台时,导航状态丢失。"

-> 该技能演示了可编码的 NavigationPath、SceneStorage 持久化和防崩溃的恢复机制

5. "我如何在 SwiftUI 中实现协调器模式?"

-> 该技能提供了路由器模式示例,并说明了协调器何时增加价值或何时增加复杂性


预警信号——需要避免的反模式

如果你正在执行以下任何操作,请立即停止并使用此技能中的模式:

❌ 关键——切勿做这些

1. 在 iOS 16+ 上使用已弃用的 NavigationView

// ❌ 错误——已弃用,iOS 16+ 上行为不同
NavigationView {
    List { ... }
}
.navigationViewStyle(.stack)

为什么失败 NavigationView 自 iOS 16 起已弃用。它缺乏 NavigationPath 支持,导致程序化导航和深层链接不可靠。不同 iOS 版本上的不同行为会导致 Bug。

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))

为什么失败 用户可能已删除路径中的项目。模式可能已更改。强制解包会导致恢复时崩溃。


强制性第一步

在实现导航之前,始终完成以下步骤:

// 第一步:确定你的导航结构
// 问:单堆栈?多列?每个标签有各自导航的基于标签的应用?
// 在编写任何代码之前记录答案

// 第二步:根据结构选择容器
// 单堆栈(优先考虑 iPhone):NavigationStack
// 多列(优先考虑 iPad/Mac):NavigationSplitView
// 基于标签:TabView,每个标签一个 NavigationStack

// 第三步:为导航定义你的值类型
// 在 NavigationStack 上推送的所有值必须为 Hashable
// 对于深层链接/恢复,也需要 Codable
struct Recipe: Hashable, Codable, Identifiable { ... }

// 第四步:规划深层链接 URL(如果需要)
// myapp://recipe/{id}
// myapp://category/{name}/recipe/{id}

// 第五步:规划状态恢复(如果需要)
// 你会使用 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:每个标签带独立 NavigationStack 的 TabView

何时使用:基于标签的应用,每个标签有自己的导航

时间成本: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()
                }
            }
        }
    }
}

关键点:

  • 每个标签都有自己的 NavigationStack
  • 切换标签时导航状态得以保留
  • iOS 18+ 带 systemImage 的 Tab 语法

模式 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:状态恢复

何时使用:应用进入后台时需要保留导航状态

时间成本:20-30 分钟

struct ContentView: View {
    @SceneStorage("navigationPath") private var navigationPathData: Data?
    @State private var path = NavigationPath()

    var body: some View {
        NavigationStack(path: $path) {
            // ... 视图内容
        }
        .task {
            // 恢复路径
            if let data = navigationPathData {
                do {
                    let codable = try JSONDecoder().decode(NavigationPath.CodableRepresentation.self, from: data)
                    path = NavigationPath(codable)
                } catch {
                    // 解码失败时优雅降级
                    print("Failed to restore navigation path: \(error)")
                }
            }
        }
        .onChange(of: path.codable) { _, newValue in
            // 持久化路径
            guard let codable = newValue else { return }
            navigationPathData = try? JSONEncoder().encode(codable)
        }
    }
}

关键点:

  • 使用 SceneStorage 持久化可编码的路径表示
  • 始终处理解码错误——决不强解包
  • 使用 ID 而非完整模型对象进行恢复

模式 7:路由器模式

何时使用:控制逻辑复杂、需要测试或跨屏幕共享

时间成本:30-60 分钟

@MainActor
@Observable
class Router {
    var path = NavigationPath()

    func navigate(to destination: any Hashable) {
        path.append(destination)
    }

    func goBack() {
        guard !path.isEmpty else { return }
        path.removeLast()
    }

    func popToRoot() {
        path.removeLast(path.count)
    }

    func handleDeepLink(_ url: URL) { ... }
}

struct AppView: View {
    @State private var router = Router()

    var body: some View {
        NavigationStack(path: Bindable(router).path) {
            ContentView()
                .navigationDestination(for: Recipe.self) { recipe in
                    RecipeDetail(recipe: recipe)
                }
        }
        .environment(router)
    }
}

关键点:

  • 路由器类必须带有 @MainActor 注解,用于 Swift 6 并发
  • 在 SwiftUI 视图之外或跨视图共享导航逻辑
  • 使深层链接处理集中化且可测试

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

相关技能