Search code examples
iosswift3uiviewcontrollerchildviewcontroller

How to remove a VC then add another VC directly afterward


I have a Main VC (call this VC A), that has a child VC (VC B). When I tap a button on VC B I dismiss it as a child VC, however once this is done I would like to instantiate another VC (VC C). I do this by creating a bool on VC B which, if true calls a function on VC A that creates a new child VC (VC C). All of the function calls are being made however the VC C never gets added. Below I have added the code:

VC B:

 func removeAnimate()
{

    self.willMove(toParentViewController: nil)
    self.view.removeFromSuperview()
    self.removeFromParentViewController()

    didTransition = true

    if didTransition == true {
       callAddVC()
    }

}

func callAddVC() {
    let instVC = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "MainViewController") as! MainViewController

    instVC.addVC()
}

VC A:

  func addVC () {


    let popvc = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "CommentsTabViewController") as! CommentsTabViewController

    self.addChildViewController(popvc)
    popvc.view.center = self.view.center

    popvc.view.bounds.size = CGSize(width: 337, height: 503)

    self.view.addSubview(popvc.view)

    popvc.didMove(toParentViewController: self)
            }

Solution

  • You are creating new instance of ViewController A (MainViewController) on the callAddVC(), Which is wrong. You are not using existing instance of the ViewController A

    You have to pass the Viewcontroller A instance while adding a Viewcontroller B

    Viewcontroller A

      let viewControllerB = // Get the instance of UIViewControllerB from storyboard
      viewControllerB.vcA = self
    

    Viewcontroller B

      class UIViewControllerB {
            weak var vcA: UIViewControllerA?
    
             func removeAnimate() {
    
                  self.willMove(toParentViewController: nil)
                  self.view.removeFromSuperview()
                  self.removeFromParentViewController()
    
                  didTransition = true
    
                 if didTransition == true {
                   vcA.addVC(). //You have to call addVC() by using the reference of the main view controller.
                 }
               }
    
         }