簡體   English   中英

從模態呈現的視圖控制器導航到根視圖控制器

[英]Navigate to root view-controller from modally presented view controller

我有以下場景。

根視圖控制器 - A

推視圖控制器 - B

呈現的視圖控制器 - C

A -> 推 B。

B -> 呈現 C.

我怎樣才能從C回到A。

您可以在 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)
}

如何?

要做到這一點,你將不得不通過控制器呈現UINavigationController一個變量視圖控制器你present -ing。 讓我告訴你如何,以及結果。

vcA推到vcB是相當簡單的。 需要注意的一件事是,當您從vcA推送到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)
}

結果

在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM