如何一次关闭多个viewcontroller?

How to close multiple viewcontrollers in one time?

根据我的要求,我必须返回到我的 rootviewcontroller (tabbar),但上面有很多页面。

示例流程

我的标签栏(有 4 个标签,每个标签都有自己的导航)-> push(vc1) -> present nav(vc2) -> push vc3 -> present nav(vc4)

如果我想关闭所有 viewcontroller ( vc1 - vc4 ) 如何通过一个函数关闭它们?

如果您想直接转到第一个 viewController:

self.popToRootViewController(animated: true)

如果你想看看它是如何消失的

@objc func buttonPressed() {
        
        let viewControllers: [UIViewController] = self.viewControllers

        for aViewController in viewControllers {
            self.popViewController(animated: true)
        }
        
        self.popToRootViewController(animated: true)
    }

您可以在从标签栏(根级别)开始呈现的基础视图控制器上使用 UIViewController.dismiss(animated:completion:) 调用。

If you present several view controllers in succession, thus building a stack of presented view controllers, calling this method on a view controller lower in the stack dismisses its immediate child view controller and all view controllers above that child on the stack. When this happens, only the top-most view is dismissed in an animated fashion; any intermediate view controllers are simply removed from the stack. The top-most view is dismissed using its modal transition style, which may differ from the styles used by other view controllers lower in the stack.

鉴于此层次结构

my tabbar (have 4 tabs each tab has own navigation ) -> push(vc1) -> present nav(vc2) -> push vc3 -> present nav(vc4)

您可以像下面这样返回演示层次结构 -

let vc4Presenter = vc4.navigationController?.presentingViewController

let vc2NavCtrl = (vc4Presenter as? UINavigationController) ?? vc4Presenter?.navigationController
let vc2Presenter = vc2NavCtrl?.presentingViewController

let vc1NavCtrl = (vc2Presenter as? UINavigationController) ?? vc2Presenter?.navigationController
vc2Presenter?.dismiss(animated: true, completion: {
    vc1NavCtrl?.popToRootViewController(animated: false)
})

以上只是您如何找到正确的视图控制器实例以在视图层次结构中调用 dismiss 的示例。这绝对不适合动态数量的表示层。

你可以-

  1. 以递归的方式写这个(这样它会一直寻找 presentingViewController 直到找到根级别的 nil)。
  2. 在整个应用程序中方便地引用选项卡栏控制器,并在其当前选择的视图控制器(选项卡)上调用关闭。