首页 > 解决方案 > 从模态呈现的视图控制器导航到根视图控制器

问题描述

我有以下情况。

根视图控制器 - A

推送视图控制器 - B

提出的视图控制器 - C

A -> 推 B。

B -> 呈现 C。

我怎样才能从C回到A。

标签: iosswiftuinavigationcontrollerpushviewcontrollerpresentviewcontroller

解决方案


如何?

为此,您必须将呈现控制器UINavigationController作为变量传递给您正在使用的视图控制器present。让我告诉你如何,以及结果。

vcA到推动vcB是相当直截了当的。需要注意的一件事是,当您从vcAto推送时vcBvcA将位于导航堆栈中。考虑到这一点,让我移动一个。

首先vcC通过添加一个变量来保存所UINavigationCongroller呈现的视图控制器的vcC,这将是vcB。执行以下操作(阅读评论)

class ViewControllerC: UIViewController {

    // Variable that holds reference to presenting ViewController's Navigtion controller
    var presentingNavigationController: UINavigationController!

    //Some action that triggers the "Go-back-to-A"
    @objc func pressed() {
        // When the completion block is executed in dismiss,
        // This function will loop through all ViewControllers in the presenting Navigation stack to see if vcA exists
        // Since vcA was earlier pushed to the navigation stack it should exist
        // So we can use the same navigation controller to pop to vcA    
        // Set the animated property to false to make the transition instant
        dismiss(animated: false) {
            self.presentingNavigationController.viewControllers.forEach({
                if let vc = $0 as? ViewController {
                    self.presentingNavigationController.popToViewController(vc, animated: true)
                }
            })
        }
    }

您可以在vcB其中添加以下present(_:_:_:)功能

// function call
@objc func pressed() {
    let vc = ViewControllerC()
    // Setting the navigation controller for reference in the presented controller
    vc.presentingNavigationController = self.navigationController  
    present(vc, animated: true, completion: nil)
}

结果

在此处输入图像描述


推荐阅读