如何在SwiftUI中通过条件使用.navigationDestination实现视图导航?
可行,实现方法如下
这种基于NavigationStack和.navigationDestination的链式导航完全可行,核心是通过统一注册导航目标+分场景触发导航来实现你的流程。下面是具体实现步骤和代码示例:
1. 定义场景枚举(区分SuccessfulView的不同状态)
先创建一个枚举标记SuccessfulView的两种场景,方便导航时传递状态:
enum SuccessScene { case verifyPhoneNumber case setPinCode }
2. 构建导航栈根视图,注册所有导航目标
在根视图中使用NavigationStack,通过.navigationDestination注册所有需要跳转的视图类型:
struct RootView: View { // 用绑定数组管理导航路径,方便统一控制栈行为 @State private var navigationPath: [AnyHashable] = [] var body: some View { NavigationStack(path: $navigationPath) { VerifyPhoneNumberView(navigationPath: $navigationPath) // 注册SuccessScene对应的导航目标 .navigationDestination(for: SuccessScene.self) { scene in SuccessfulView(scene: scene, navigationPath: $navigationPath) } // 注册SetPinCodeView的导航目标 .navigationDestination(for: SetPinCodeView.self) { _ in SetPinCodeView(navigationPath: $navigationPath) } // 注册OtherView的导航目标 .navigationDestination(for: OtherView.self) { _ in OtherView() } } } }
3. 实现各视图的导航触发逻辑
每个视图通过修改绑定的navigationPath来触发跳转:
VerifyPhoneNumberView(导航起点)
struct VerifyPhoneNumberView: View { @Binding var navigationPath: [AnyHashable] var body: some View { VStack(spacing: 20) { Text("验证手机号") .font(.title) Button("完成手机号验证") { // 跳转到验证成功场景的SuccessfulView navigationPath.append(SuccessScene.verifyPhoneNumber) } .buttonStyle(.borderedProminent) } } }
SuccessfulView(分场景展示)
根据传入的SuccessScene展示不同内容和跳转按钮:
struct SuccessfulView: View { let scene: SuccessScene @Binding var navigationPath: [AnyHashable] var body: some View { VStack(spacing: 20) { Text(scene == .verifyPhoneNumber ? "手机号验证成功!" : "PIN码设置成功!") .font(.title) .bold() if scene == .verifyPhoneNumber { Button("前往设置PIN码") { navigationPath.append(SetPinCodeView()) } } else { Button("进入后续页面") { navigationPath.append(OtherView()) } } .buttonStyle(.borderedProminent) } } }
SetPinCodeView
struct SetPinCodeView: View { @Binding var navigationPath: [AnyHashable] var body: some View { VStack(spacing: 20) { Text("设置PIN码") .font(.title) TextField("输入6位PIN码", text: .constant("")) .textFieldStyle(.roundedBorder) .frame(width: 200) Button("完成PIN码设置") { // 跳转到PIN码设置成功场景的SuccessfulView navigationPath.append(SuccessScene.setPinCode) } .buttonStyle(.borderedProminent) } } }
OtherView(最终页面)
struct OtherView: View { var body: some View { Text("后续功能页面") .font(.title) } }
关键注意事项
- 确保项目适配iOS 16+,因为
.navigationDestination和NavigationStack是iOS 16引入的API。 - 如果需要传递业务数据,可以给
SuccessScene添加关联值,比如case verifyPhoneNumber(userID: String),方便在SuccessfulView中接收使用。 - 通过绑定的
navigationPath可轻松实现栈操作,比如navigationPath.removeLast()返回上一页,navigationPath.removeAll()回到根视图。
内容的提问来源于stack exchange,提问作者Suweey
相关产品推荐
相关产品推荐

