Communitygithub.com

ComeOnOliver/skillshub

用于调试导航无响应、意外弹窗、深层链接显示错误页面、切换标签或进入后台时状态丢失、navigationDestination 崩溃等任何 SwiftUI 导航故障——提供系统化诊断与生产危机防御。

skillshub 是什么?

这个 AI 技能提供了一套系统化的 SwiftUI 导航诊断框架。它遵循一个核心原则:85% 的导航问题源于路径状态管理错误、视图标识问题或布局错误,而非 SwiftUI 框架本身的缺陷。该技能通过强制性的第一步诊断(如添加 NavigationPath 日志记录、检查 navigationDestination 是否可见以及验证 NavigationLink 是否在 NavigationStack 内部)帮助开发者快速定位问题根源。它包含详细的决策树,可根据具体症状(如导航点击无反应、意外返回、深层链接失败、状态丢失或崩溃)引导用户找到正确的诊断模式(共 5 大类,涵盖 15+ 种具体模式)。每个模式都提供了明确的症状、诊断方法、修复方案和验证步骤。该技能特别强调“禁止”在没有诊断的情况下猜测解决方案,并警告了常见的反模式,例如用 UINavigationController 包装“因为 SwiftUI 出问题了”。它主要支持在 Swift 和 SwiftUI 开发环境中使用,适用于 Xcode 项目开发,帮助开发者节省数小时的调试时间。

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

在你喜欢的 AI 中提问

打开一个已预加载此 Agent Skill 的新对话。

文档

SwiftUI 导航诊断

概述

核心原则 85% 的导航问题源于路径状态管理错误、视图标识问题或布局错误——而非 SwiftUI 框架缺陷。

SwiftUI 的导航系统被数百万应用使用,能够可靠地处理复杂的导航模式。如果你的导航失败、无响应或行为异常,问题几乎总是出在你管理导航状态的方式上,而不是框架本身。

本技能提供系统化的诊断方法,帮助你在几分钟内(而不是数小时)找到根本原因。

红旗标志——怀疑导航问题

如果你看到以下任何一种情况,请怀疑是代码问题,而非框架错误:

  • 导航点击无响应(链接存在但不会推入)

  • 返回按钮弹出到错误的页面或根页面

  • 深层链接打开应用但显示错误的页面

  • 切换标签页时导航状态丢失

  • 应用进入后台再返回时导航状态丢失

  • 同一个 NavigationLink 推入两次

  • 导航动画卡住或卡顿

  • 崩溃,堆栈跟踪中出现 navigationDestination

  • ❌ 禁止 “SwiftUI 导航坏了,我们改用 UINavigationController 包装吧”

    • Apple 自己的应用也在使用 NavigationStack
    • 包装 UIKit 会增加复杂性并失去 SwiftUI 状态管理的优势
    • UIKit 互操作有自己的一系列边界情况,你会花几周时间去发现
    • 你的问题几乎肯定是路径管理问题,而不是框架缺陷

关键区别 NavigationStack 的行为是确定性的。如果它不工作,说明你修改状态的方式不正确,存在视图标识问题,或者 navigationDestination 放置位置错误。

强制性的第一步

始终先运行这些检查(在修改代码之前):

// 1. 添加 NavigationPath 日志记录
NavigationStack(path: $path) {
    RootView()
        .onChange(of: path.count) { oldCount, newCount in
            print("📍 路径已更改:\(oldCount) → \(newCount)")
            // 如果这个从不触发,说明链接没有修改路径
            // 如果它意外触发,说明有其他代码修改了路径
        }
}

// 2. 检查 navigationDestination 是否可见
// 在目标闭包中放置临时打印语句
.navigationDestination(for: Recipe.self) { recipe in
    let _ = print("🔗 Recipe 的目标视图:\(recipe.name)")
    RecipeDetail(recipe: recipe)
}
// 如果这个从不打印,说明目标视图未被评估

// 3. 检查 NavigationLink 是否在 NavigationStack 内部
// 目视检查:从 NavigationLink 向上追溯视图层级
// 必须命中 NavigationStack,而不是先遇到其他容器

// 4. 检查路径状态位置
// @State 必须位于稳定的视图中(不会在每次渲染时重建)
// 必须是 @State、@StateObject 或 @Observable —— 不能是局部变量

// 5. 隔离测试基本情况
// 创建最小化重现
NavigationStack {
    NavigationLink("测试", value: "test")
        .navigationDestination(for: String.self) { str in
            Text("已推入:\(str)")
        }
}
// 如果这个正常工作,问题出在你的特定设置上

这告诉你什么

观察结果诊断下一步
点击后 onChange 从不触发NavigationLink 不在 NavigationStack 层级中模式 1a
onChange 触发但视图不推入navigationDestination 未找到/未加载模式 1b
onChange 触发,视图推入,然后立即弹出视图标识问题或路径被修改模式 2a
路径意外更改(非点击引起)外部代码修改路径模式 2b
deep link 的 path.append() 不导航时机问题或线程错误模式 3b
切换标签页时状态丢失NavigationStack 在标签页间共享模式 4a
第一次工作,返回后失败视图重建问题模式 5a

强制性的解释

在修改任何代码之前,确定以下一个问题:

  1. 如果点击链接无反应且没有 onChange → 链接在 NavigationStack 外部(检查层级)
  2. 如果 onChange 触发但无推入视图 → navigationDestination 不在作用域内(检查放置位置)
  3. 如果推入后立即弹出 → 视图标识更改或路径重置(检查 @State 位置)
  4. 如果深层链接失败 → 时机或 MainActor 问题(检查线程)
  5. 如果崩溃 → 路径解码时强制解包或缺少类型注册

如果诊断结果矛盾或不明确

  • 停止。暂时不要进入模式
  • 在每个路径修改点添加打印语句
  • 创建最小化重现案例
  • 首先使用 String 值进行测试(最简单的情况)

决策树

在 2 分钟内使用此决策树找到正确的诊断模式:

导航问题?
├─ 导航点击无响应?
│  ├─ NavigationLink 在 NavigationStack 内部?
│  │  ├─ 否 → 模式 1a(链接在 Stack 外部)
│  │  └─ 是 → 检查 navigationDestination
│  │
│  ├─ navigationDestination 已注册?
│  │  ├─ 在懒加载容器内部?→ 模式 1b(懒加载)
│  │  ├─ 类型不匹配?→ 模式 1c(类型注册)
│  │  └─ 被 sheet/popover 阻塞?→ 模式 1d(模态阻塞)
│  │
│  └─ 使用基于视图的链接?
│     └─ → 模式 1e(废弃的 API)
│
├─ 意外返回?
│  ├─ 推入后立即弹出?
│  │  ├─ 视图 body 重建 path?→ 模式 2a(Path 重建)
│  │  ├─ @State 在错误的视图中?→ 模式 2a(状态位置)
│  │  └─ ForEach id 变更?→ 模式 2c(标识变更)
│  │
│  ├─ 在不该返回时返回?
│  │  ├─ 外部代码调用 removeLast?→ 模式 2b(意外修改)
│  │  ├─ Task 被取消?→ 模式 2b(异步取消)
│  │  └─ MainActor 问题?→ 模式 2d(线程)
│  │
│  └─ 返回按钮行为不正确?
│     └─ → 模式 2e(栈损坏)
│
├─ 深层链接不工作?
│  ├─ URL 未收到?
│  │  ├─ onOpenURL 未调用?→ 检查 Info.plist 中的 URL scheme
│  │  └─ Universal Links 问题?→ 检查 apple-app-site-association
│  │
│  ├─ URL 已收到,但路径未更新?
│  │  ├─ path.append 不在 MainActor 上?→ 模式 3a(线程)
│  │  ├─ 时机问题(应用未就绪)?→ 模式 3b(初始化)
│  │  └─ NavigationStack 尚未创建?→ 模式 3b(生命周期)
│  │
│  └─ 路径已更新,但显示错误的页面?
│     ├─ 路径顺序错误?→ 模式 3c(路径构建)
│     ├─ 追加了错误的类型?→ 模式 3c(类型不匹配)
│     └─ 项目未找到?→ 模式 3d(数据解析)
│
├─ 状态丢失?
│  ├─ 切换标签页时丢失?
│  │  ├─ 共享的 NavigationStack?→ 模式 4a(共享状态)
│  │  └─ 标签页重建?→ 模式 4a(标签页标识)
│  │
│  ├─ 进入/退出后台时丢失?
│  │  ├─ 没有 SceneStorage?→ 模式 4b(无持久化)
│  │  └─ 解码失败?→ 模式 4c(解码错误)
│  │
│  └─ 旋转/尺寸变化时丢失?
│     └─ → 模式 4d(布局重建)
│
├─ NavigationSplitView 问题?
│  ├─ iPad 上侧边栏不可见?
│  │  ├─ columnVisibility 未设置?→ 模式 6a(列可见性)
│  │  └─ 紧凑尺寸类别?→ 模式 6a(自动适配)
│  │
│  ├─ iPad 上详情页显示空白?
│  │  ├─ 没有默认的详情视图?→ 模式 6b(缺失详情)
│  │  └─ Selection 绑定为 nil?→ 模式 6b(选择状态)
│  │
│  └─ 在 iPhone 上工作,在 iPad 上损坏?
│     └─ → 模式 6c(平台适配)
│
└─ 崩溃?
   ├─ 导航代码中的 EXC_BAD_ACCESS?
   │  └─ → 模式 5a(内存问题)
   │
   ├─ 致命错误:类型未注册?
   │  └─ → 模式 5b(缺失目标视图)
   │
   └─ 恢复时解码失败?
      └─ → 模式 5c(恢复崩溃)

模式选择规则(强制)

在进入某个模式之前:

  1. 导航点击无响应 → 首先添加 onChange 日志记录,然后进入模式 1
  2. 意外返回 → 找到是什么在修改路径(日志记录),然后进入模式 2
  3. 深层链接失败 → 验证 URL 是否已接收(在 onOpenURL 中打印),然后进入模式 3
  4. 状态丢失 → 确定何时丢失(标签页切换 vs 进入后台),然后进入模式 4
  5. 崩溃 → 获取完整堆栈跟踪,然后进入模式 5

一次只应用一个模式

  • 实现一个模式中的修复
  • 进行全面测试
  • 仅当问题仍然存在时,再尝试下一个模式
  • 不要同时应用多个模式(无法隔离原因)

禁止

  • 没有诊断就猜测解决方案
  • 一次更改多个内容
  • 用 UINavigationController 包装“因为 SwiftUI 出问题了”
  • 在不理解原因的情况下添加延迟/DispatchQueue.main.async
  • 切换到基于视图的 NavigationLink“以避免路径问题”

诊断模式

模式 1a:NavigationLink 在 NavigationStack 外部

时间成本 5-10 分钟

症状

  • 点击 NavigationLink 无响应
  • 没有导航发生,没有错误
  • onChange(of: path) 从不触发

诊断

// 检查视图层级 — NavigationLink 必须在 NavigationStack **内部**

// ❌ 错误——链接在 stack 外部
struct ContentView: View {
    var body: some View {
        VStack {
            NavigationLink("Go", value: "test")  // 在 stack 外部!
            NavigationStack {
                Text("Root")
            }
        }
    }
}

// 检查:为 NavigationStack 添加背景色
NavigationStack {
    Color.red  // 如果链接在红色区域上,则它在内部
}

修复

// ✅ 正确——链接在 stack 内部
struct ContentView: View {
    var body: some View {
        NavigationStack {
            VStack {
                NavigationLink("Go", value: "test")  // 在 stack 内部
                Text("Root")
            }
            .navigationDestination(for: String.self) { str in
                Text("已推入:\(str)")
            }
        }
    }
}

验证

  • 点击链接,导航发生
  • 点击时 onChange(of: path) 触发

模式 1b:navigationDestination 在懒加载容器中

时间成本 10-15 分钟

症状

  • NavigationLink 点击无响应或间歇性工作
  • onChange 触发(路径已更新)但视图不推入
  • 控制台可能显示:“A navigationDestination for [Type] was not found”

诊断

// ❌ 错误——目标视图在懒加载容器中(可能未被加载)
ScrollView {
    LazyVStack {
        ForEach(items) { item in
            NavigationLink(item.name, value: item)
                .navigationDestination(for: Item.self) { item in
                    ItemDetail(item: item)  // 可能未被评估!
                }
        }
    }
}

修复

// ✅ 正确——目标视图放在懒加载容器外部
ScrollView {
    LazyVStack {
        ForEach(items) { item in
            NavigationLink(item.name, value: item)
        }
    }
}
.navigationDestination(for: Item.self) { item in
    ItemDetail(item: item)  // 始终可用
}

验证

  • 在目标闭包中添加打印——导航时应该总是打印
  • 无论滚动位置如何都能工作

模式 1c:类型注册不匹配

时间成本 10 分钟

症状

  • 导航点击无响应
  • 没有与值类型匹配的 navigationDestination
  • 可能某些链接有效,其他无效

诊断

// 检查:值类型必须**完全**匹配目标类型

// 链接使用 Recipe
NavigationLink(recipe.name, value: recipe)  // value 是 Recipe

// 目标视图注册为... Recipe.ID?
.navigationDestination(for: Recipe.ID.self) { id in  // ❌ 错误类型!
    RecipeDetail(id: id)
}

修复

// 精确匹配类型
NavigationLink(recipe.name, value: recipe)  // Recipe

.navigationDestination(for: Recipe.self) { recipe in  // ✅ Recipe
    RecipeDetail(recipe: recipe)
}

// 或者修改链接以使用 ID
NavigationLink(recipe.name, value: recipe.id)  // Recipe.ID

.navigationDestination(for: Recipe.ID.self) { id in  // ✅ Recipe.ID
    RecipeDetail(id: id)
}

验证

  • 在目标视图内打印类型:print(type(of: value))
  • 类型必须完全匹配(无继承)

模式 2a:NavigationPath 每次渲染时重建

时间成本 15-20 分钟

症状

  • 导航推入后立即返回
  • 目标视图似乎“闪烁”一下
  • 第一次工作,然后失败,或立即失败

诊断

// ❌ 错误——Path 在视图 body 中创建(每次渲染重置)
struct ContentView: View {
    var body: some View {
        let path = NavigationPath()  // 每次重新创建!
        NavigationStack(path: .constant(path)) {
            // ...
        }
    }
}

// ❌ 错误——@State 在子视图中,被子视图重建
struct ParentView: View {
    @State var showChild = true
    var body: some View {
        if showChild {
            ChildView()  // 当 showChild 切换时重建
        }
    }
}

struct ChildView: View {
    @State var path = NavigationPath()  // 当 ChildView 重建时丢失
    // ...
}

修复

// ✅ 正确——@State 在稳定层级
struct ContentView: View {
    @State private var path = NavigationPath()  // 在渲染之间持久化

    var body: some View {
        NavigationStack(path: $path) {
            RootView()
        }
    }
}

// ✅ 正确——@StateObject 用于 ObservableObject
struct ContentView: View {
    @StateObject private var navModel = NavigationModel()

    var body: some View {
        NavigationStack(path: $navModel.path) {
            RootView()
        }
    }
}

验证

  • 添加 onChange 日志记录——路径不应意外重置
  • 导航,等待,path.count 保持稳定

模式 2d:在 MainActor 之外修改路径

时间成本 10-15 分钟

症状

  • 导航有时有效,有时无效
  • Swift 6 关于 MainActor 隔离的警告
  • 意外返回或状态损坏

诊断

// ❌ 错误——在后台任务中修改路径
func loadAndNavigate() async {
    let recipe = await fetchRecipe()
    path.append(recipe)  // ⚠️ 不在 MainActor 上!
}

// 检查:搜索 path.append, path.removeLast 在 @MainActor 上下文之外的地方

修复

// ✅ 正确——确保在 MainActor 上
@MainActor
func loadAndNavigate() async {
    let recipe = await fetchRecipe()
    path.append(recipe)  // ✅ MainActor 隔离
}

// 或显式调度
func loadAndNavigate() async {
    let recipe = await fetchRecipe()
    await MainActor.run {
        path.append(recipe)
    }
}

// ✅ 最佳——使用 @Observable 和 @

[为简洁起见截断了更多模式]


生产防御

崩溃报告实时监控

在崩溃发生之前捕获它们,使用以下工具:

// 添加路径状态监控
NavigationStack(path: $path) {
    // ...
        .onChange(of: path.count) { old, new in
            // 在生产环境中记录路径状态
            #if DEBUG
            print("📍 路径更改:\(old) → \(new)")
            #endif
        }
}

// 使用 ScenarioStorage 实现崩溃恢复
struct ContentView: View {
    @SceneStorage("navigation.path") private var pathData: Data?
    @State private var path: NavigationPath

    init() {
        if let data = pathData {
            // 尝试解码
            // 如果失败,回退到空路径
        }
    }
}

测试策略

  1. 单元测试:测试路径状态变更,不测试视图
  2. UI 测试:使用 XCUITest 验证真实导航流程
  3. 内存泄漏检测:使用 Instruments 的 Leaks 模板
  4. 边缘情况:快速点击、后台恢复、内存警告

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

相关技能