You need to enable JavaScript to run this app. Swift中如何通过segue跳转至导航控制器根视图重启表单流程?
优惠活动
大模型
产品
解决方案
定价
更多

Swift中如何通过segue跳转至导航控制器根视图重启表单流程?

你遇到的问题核心原因是:普通的正向Segue跳转是把新的ViewController压入导航栈,原有栈内的所有页面(screen2、screen3、screen4)都还保留,所以跳转后返回按钮仍然能回到screen4。你需要的是清空跳转前的表单页面栈,而不是叠加新页面。

参考配置图:
配置示意图

解决方案

方法1:使用Unwind Segue(最符合Storyboard设计规范的方案)

  • 第一步:在screen1对应的ViewController代码中添加Unwind回调方法,示例如下:
@IBAction func unwindToScreen1(segue: UIStoryboardSegue) {
    // 此处可添加表单数据重置逻辑
}
  • 第二步:打开screen4所在的Storyboard,按住Control键拖动screen4的触发按钮到当前ViewController顶部的「退出」图标(Storyboard场景顶部三个图标最右侧的带箭头出口图标),在弹出的方法列表中选择刚才添加的unwindToScreen1,自动生成Unwind Segue
  • 第三步:给该Segue设置唯一的Identifier(如unwindToFormStart),如需传参可在screen4的prepare(for:sender:)方法中处理

该方案会自动弹出导航栈中screen1之后的所有ViewController,跳转后导航栈仅保留screen1,完全符合重启表单流程的需求。

方法2:代码直接重置导航栈(无需配置Segue)

如果不想通过Storyboard配置Segue,可以直接在screen4的按钮点击事件中替换导航控制器的ViewController栈:

Swift 示例代码

@IBAction func restartFormTapped(_ sender: UIButton) {
    // 从Storyboard1实例化screen1
    let sb1 = UIStoryboard(name: "Storyboard1", bundle: nil)
    guard let screen1VC = sb1.instantiateViewController(withIdentifier: "Screen1VCID") as? Screen1ViewController else { return }
    // 直接替换导航栈
    navigationController?.setViewControllers([screen1VC], animated: true)
}

Objective-C 示例代码

- (IBAction)restartFormTapped:(UIButton *)sender {
    UIStoryboard *sb1 = [UIStoryboard storyboardWithName:@"Storyboard1" bundle:nil];
    Screen1ViewController *screen1VC = [sb1 instantiateViewControllerWithIdentifier:@"Screen1VCID"];
    if (screen1VC) {
        [self.navigationController setViewControllers:@[screen1VC] animated:YES];
    }
}

注意:需要提前在Storyboard1中给screen1对应的ViewController设置Storyboard ID,和代码中的Screen1VCID保持一致。

方法3:直接弹出到根控制器(仅适用于screen1是当前导航栈根VC的场景)

如果你的整个表单流程都运行在同一个导航控制器下,且screen1就是该导航控制器的根ViewController,可以直接调用系统的弹出到根方法,代码最简单:

// Swift
navigationController?.popToRootViewController(animated: true)
// Objective-C
[self.navigationController popToRootViewControllerAnimated:YES];

内容的提问来源于stack exchange,提问作者7hero

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.09 20:42:02