iosswiftuiviewcontrolleruinavigationcontrollerpopviewcontroller

(Swift) popping back to navigation controller


I will describe what I want to do. I have 3 viewControllers. The first one should be navigation one, and I think I have made mistake there in code.
First VC leads to Second, and the second VC leads to Third VC.The third one has got a button which should lead back to the first one.

This is how I present secondVC from the firstVC:

let mainStoryboard = UIStoryboard(name: "Main", bundle: Bundle.main)
let secondVC = (mainStoryboard.instantiateViewController(withIdentifier: "SecondViewController") as! SecondViewController)   
presentVC(SecondVC)

func presentVC(_ VC: UIViewController) {
        let navController = UINavigationController(rootViewController: VC)
        navController.modalPresentationStyle = .fullScreen
        self.navigationController?.present(navController, animated: true, completion: nil)
    }

Now in the secondVC, when I click Close in right navBarItem, the thirdVC should be opened and it works fine, here is the code:

In ViewDidLoad :

 self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Close", style: .plain, target: self, action:
#selector(closeSecondVC))

And after:

  @objc
    func closeSecondVC() {
    let mainStoryboard = UIStoryboard(name: "Main", bundle: Bundle.main)
            let thirdVC = (mainStoryboard.instantiateViewController(withIdentifier: "ThirdViewController") as! ThirdViewController)
            presentVC(thirdVC) //Same function as above.
}

And on this buttonClick in the thirdVC, I need to return to firstVC, that's where I am lost:

 @IBAction func btnTapped(_ sender: Any) {
        if let navController = self.navigationController {
            navController.popViewController(animated: true)
        }  //nothing happens on click
    }

Solution

  • Use below code in btnTapped:

        for controller in self.navigationController!.viewControllers as Array 
        {
          // here YourViewController is your firstVC      
         if controller.isKind(of: YourViewController.self) {
                self.navigationController!.popToViewController(controller, animated: true)
                break
            }
        }
    

    And don't present your view push your view to pop.