多视图控制器推送与模态跳转后,如何返回TabBarController?
解决方案:直接回到TabBarController的正确做法
首先,咱们先明确你的控制器层级:
UITabBarController(首页容器)→UINavigationController→Child1(push 跳转)Child1→Child2(模态展示)Child2→Child3(模态展示)
你当前的代码问题在于:在Child2里调用的dismiss只会关闭Child3回到Child2,然后你又让Child1(self.presentingViewController)present了新控制器,这完全偏离了“回到TabBar首页”的需求。
要实现关闭Child3后直接回到TabBar首页,需要两步操作:
- 关闭所有模态弹出的控制器(
Child3+Child2),回到Child1 - 将
Child1从导航栈中弹出,回到TabBar的首页控制器
方法一:在Child3中直接处理(推荐)
在你的定时器触发方法里,添加以下代码:
// 第一步:关闭所有模态控制器,回到Child1 self.dismiss(animated: false) { // 第二步:找到Child1所在的导航控制器,弹出到根页面(TabBar首页) if let child1Nav = self.presentingViewController?.presentingViewController?.navigationController { child1Nav.popToRootViewController(animated: true) } }
方法二:更健壮的层级遍历(适合复杂场景)
如果你的控制器层级可能有变化,可以通过遍历找到最底层的TabBarController,直接完成跳转:
// 从当前控制器往上遍历,找到TabBarController func findTabBarController(from vc: UIViewController) -> UITabBarController? { var currentVC = vc while let parent = currentVC.parent { if let tabBarVC = parent as? UITabBarController { return tabBarVC } currentVC = parent } return nil } // 在定时器触发方法中调用 if let tabBarVC = findTabBarController(from: self) { // 关闭所有模态控制器 self.dismiss(animated: false) { // 将TabBar的选中导航控制器弹出到根 if let homeNav = tabBarVC.selectedViewController as? UINavigationController { homeNav.popToRootViewController(animated: true) } } }
为什么你的原代码不行?
你原代码中:
let parent = self.presentingViewController self.dismiss(animated: false, completion: { parent?.present(vc, animated: true, completion: nil) })
这里的self是Child2,self.presentingViewController是Child1,执行后只是关闭了Child3回到Child2,然后让Child1又弹出了一个新控制器,自然会停在Child1相关的页面,完全没处理导航栈的弹出操作。
内容的提问来源于stack exchange,提问作者Sarath
相关产品推荐
相关产品推荐

