         
         if fromVC != toVC && isAnimated, let fromVC = fromVC, let toVC = toVC {
             // Animated transition between view controllers
+            self.addChildViewController(toVC)
             toVC.willMoveToParentViewController(self)
             fromVC.willMoveToParentViewController(nil)
             transitionFromViewController(fromVC, toViewController: toVC, duration: animationDuration, options: animationOptions, animations: nil, completion: { isFinished in
                 fromVC.view.removeFromSuperview()
+                fromVC.didMoveToParentViewController(nil)
                 fromVC.removeFromParentViewController()
-                fromVC.didMoveToParentViewController(nil)
-                self.addChildViewController(toVC)
                 self.setupContainer(viewContainer, withViewController: toVC)
                 toVC.didMoveToParentViewController(self)
                 completion(isFinished)

    
        if fromVC != toVC, let fromVC = fromVC, let toVC = toVC {
            // Replace existing view controller with new view controller
            toVC.willMoveToParentViewController(self)
            fromVC.willMoveToParentViewController(nil)
            fromVC.view.removeFromSuperview()
            fromVC.removeFromParentViewController()
            fromVC.didMoveToParentViewController(nil)
            addChildViewController(toVC)
            setupContainer(viewContainer, withViewController: toVC)
            toVC.didMoveToParentViewController(self)
            return true
                
        } else if fromVC == nil, let toVC = toVC {
                // add new view controller
                toVC.willMoveToParentViewController(self)
                addChildViewController(toVC)
                setupContainer(viewContainer, withViewController: toVC)
                toVC.didMoveToParentViewController(self)
                return true

                // remove existing view controller
                fromVC.willMoveToParentViewController(nil)
                fromVC.view.removeFromSuperview()
                fromVC.didMoveToParentViewController(nil)
                fromVC.removeFromParentViewController()
                return true
        }
        
