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 版本 | 关键功能 |
|---|---|---|
| 2020 | iOS 14 | NavigationView(已在 iOS 16 中弃用) |
| 2022 | iOS 16 | NavigationStack, NavigationSplitView, NavigationPath, 基于值的 NavigationLink |
| 2024 | iOS 18 | Tab/侧边栏统一, sidebarAdaptable, TabSection, 缩放过渡 |
| 2025 | iOS 26 | Liquid 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 工作
- NavigationStack 维护一个
path集合 - 点击值呈现的链接会将值附加到 path 上
- NavigationStack 将
navigationDestination修饰符映射到 path 值上 - 根据目标映射将视图推入堆栈
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+