iosswiftuinavigationcontrollerpushviewcontrollerpresentviewcontroller

Navigate to root view-controller from modally presented view controller


I have the below scenario.

Root viewcontroller - A

pushed viewcontroller - B

Presented viewcontroller - C

A -> pushed B.

B -> presented C.

How can i go back to A from C.


Solution

  • You can write following inside 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)
        })
    }
    

    UPDATE

    I would like to know if is there anyway to bypass the dismiss and direct pop to root view controller. I want to avoid showing View-controller 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)
    }