How to update child controllers when adding / removing from a container controller?

I have the following 2 functions that add and remove child view controllers launched from the container controller:

@discardableResult func addChildViewController(withChildViewController childViewController: UIViewController) -> UIViewController {
    // Add Child View Controller
    addChildViewController(childViewController)
    childViewController.beginAppearanceTransition(true, animated: true)
    // Add Child View as Subview
    view.addSubview(childViewController.view)
    // Configure Child View
    childViewController.view.frame = view.bounds
    childViewController.view.autoresizingMask = [.flexibleWidth, .flexibleHeight]
    // Notify Child View Controller
    childViewController.didMove(toParentViewController: self)
    return childViewController
}
@discardableResult func removeChildViewController(withChildViewController childViewController: UIViewController) -> UIViewController {
    // Notify Child View Controller
    childViewController.willMove(toParentViewController: nil)
    childViewController.beginAppearanceTransition(false, animated: true)
    // Remove Child View From Superview
    childViewController.view.removeFromSuperview()
    // Notify Child View Controller
    childViewController.removeFromParentViewController()
    return childViewController
}

The above functions are extensions for the UIViewController, so all I do is self.addChildViewController () and self.removeChildViewController () on the parent view controller.

How do I animate a deleted view in the output and add a view in its path?

+6
source share
1 answer

Animation between different controllers of children's performance: -

func cycleFromViewController(oldViewController: UIViewController, toViewController newViewController: UIViewController) {
    oldViewController.willMove(toParentViewController: nil)
    newViewController.view.translatesAutoresizingMaskIntoConstraints = false

    self.addChildViewController(newViewController)
    self.addSubview(subView: newViewController.view, toView:self.containerView!)

    newViewController.view.alpha = 0
    newViewController.view.layoutIfNeeded()

    UIView.animate(withDuration: 0.5, delay: 0.1, options: .transitionFlipFromLeft, animations: { 
        newViewController.view.alpha = 1
        oldViewController.view.alpha = 0
    }) { (finished) in
        oldViewController.view.removeFromSuperview()
        oldViewController.removeFromParentViewController()
        newViewController.didMove(toParentViewController: self)
    }
}

In the above

  • oldViewController: - viewController
  • newViewController: - ,
  • containerView: - , .

, , FlipFromLeft UIViewAnimationOptions .

+3

All Articles