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 视图之外或跨视图共享导航逻辑
- 使深层链接处理集中化且可测试