1

我有以下情况。

根视图控制器 - A

推送视图控制器 - B

提出的视图控制器 - C

A -> 推 B。

B -> 呈现 C。

我怎样才能从C回到A。

4

2 回答 2

1

如何?

为此,您必须将呈现控制器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)
}

结果

在此处输入图像描述

于 2021-07-09T17:30:33.707 回答
0

您可以在 C 中编写以下内容

let presenting = self.presentingViewController ?? self.navigationController?.presentingViewController
let navCtrl1 = presenting as? UINavigationController // in case you presented C using b.navigationController.present...
let navCtrl2 = presenting?.navigationController // in case you presented c using b.present...
if let navCtrl = navCtrl1 ?? navCtrl2  {
    self.dismiss(animated: true, completion: {
        navCtrl.popToRootViewController(animated: true)
    })
}

更新

我想知道是否有绕过解雇和直接弹出到根视图控制器。我想避免显示视图控制器 B

let presenting = self.presentingViewController ?? self.navigationController?.presentingViewController
let navCtrl1 = presenting as? UINavigationController // in case you presented C using b.navigationController.present...
let navCtrl2 = presenting?.navigationController // in case you presented c using b.present...
if let navCtrl = navCtrl1 ?? navCtrl2  {
    navCtrl.popToRootViewController(animated: false)
    self.dismiss(animated: true, completion: nil)
}
于 2021-07-09T17:01:49.757 回答