4

Apple discusses how to have a container view controller transition between two child view controllers in this document. I would like to animate a simple push vertical slide up identical to UIModalTransitionStyleCoverVertical in UIModalTransitionStyle. However, transitionFromViewController only allows use of UIViewAnimationOptions, not transition styles. So how would one animate sliding a view up?

It's odd that to transition between child view controllers you can't call a simple push method similar in UINavigationController to animate the transition.

Apophenia Overload
  • 2,485
  • 3
  • 28
  • 46

1 Answers1

6

Load child view, set frame with origin.y under bottom screen. After change it to 0 in animation block. Example:

enum Animation {
    case LeftToRight
    case RightToLeft
}

func animationForLoad(fromvc: UIViewController, tovc: UIViewController, with animation: Animation) {

        self.addChildViewController(tovc)
        self.container.addSubview(tovc.view)
        self.currentVC = tovc

        var endOriginx: CGFloat = 0

        if animation == Animation.LeftToRight {
            tovc.view.frame.origin.x = -self.view.bounds.width
            endOriginx += fromvc.view.frame.width
        } else {
            tovc.view.frame.origin.x = self.view.bounds.width
            endOriginx -= fromvc.view.frame.width
        }

        self.transition(from: fromvc, to: tovc, duration: 0.35, options: UIViewAnimationOptions.beginFromCurrentState, animations: {
            tovc.view.frame = fromvc.view.frame
            fromvc.view.frame.origin.x = endOriginx
            }, completion: { (finish) in
                tovc.didMove(toParentViewController: self)
                fromvc.view.removeFromSuperview()
                fromvc.removeFromParentViewController()               
        })           
    }

Above code is transition between 2 child view with push and pop horizontal animation.

Dan
  • 140
  • 1
  • 6
  • It's required to have a common base view controller. It's giving me an error (crashes) as I don't have the common base view controllers. – Hemang Aug 30 '17 at 10:08
  • The accepted answer was indeed right, with just a little warning from the compiler. Using the above code you'll get a warning about unbalanced begin/end calls during the transition. This is due to Apple UIViewController.trasition method, as to apple docs: >This method adds the second view controller's view to the view hierarchy and then >performs the animations defined in your animations block. After the animation >completes, it removes the first view controller's view from the view hierarchy. In order to avoid this waring you simply need to remove the addSubview method before calling the – Simone Figliè Apr 15 '19 at 14:31