You need to enable JavaScript to run this app. 能否push到指定ViewController并加入其所属navigationController导航栈
优惠活动
大模型
产品
解决方案
定价
更多

能否push到指定ViewController并加入其所属navigationController导航栈

问题解答

你的需求完全可以实现,以下是现有代码的问题和正确实现方案:

现有代码问题

  • 类型拼写错误:自定义导航类名为MyNavigation,但代码中尝试转换为Myavigation(缺少字母N),类型转换必然失败,最终得到的navigation变量为nil,调用push方法没有任何效果
  • 导航实例错误:通过UINavigationController()初始化的是全新的空导航控制器,不是你在storyboard中配置了MyNavigation类、关联了A控制器的原有导航实例
  • 栈结构不符合需求:就算拿到了正确的导航实例,直接push B的话导航栈里只有B,点击返回按钮也不会回到A,需要提前把A控制器加入导航栈的前序位置

正确实现方案

场景1:原有导航栈未初始化,需要从C模态弹出包含A、B的导航栈

首先给storyboard中你的自定义MyNavigation导航控制器设置Storyboard ID为MyNavigationID,给Class A设置Storyboard ID为ClassAID,使用以下代码:

let storyboard = UIStoryboard(name: "MyStoryboard", bundle: nil)
guard let navigation = storyboard.instantiateViewController(withIdentifier: "MyNavigationID") as? MyNavigation,
      let aVC = storyboard.instantiateViewController(withIdentifier: "ClassAID") as? ClassA,
      let bVC = storyboard.instantiateViewController(withIdentifier: "MyId") as? FirmwareViewController else { return }

// 设置导航栈顺序,保证B返回时跳转到A
navigation.viewControllers = [aVC, bVC]

// 从当前Class C模态弹出导航控制器
present(navigation, animated: true)

场景2:原有导航栈已经是App根控制器,且栈内已经存在A控制器

可以直接获取现有导航实例push B即可:

let storyboard = UIStoryboard(name: "MyStoryboard", bundle: nil)
guard let navigation = UIApplication.shared.keyWindow?.rootViewController as? MyNavigation,
      let bVC = storyboard.instantiateViewController(withIdentifier: "MyId") as? FirmwareViewController else { return }

navigation.pushViewController(bVC, animated: true)

内容的提问来源于stack exchange,提问作者Joakim Sjöstedt

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.17 00:36:01