Skip to content

Instantly share code, notes, and snippets.

@kgleong
Last active December 29, 2018 05:16
Show Gist options
  • Save kgleong/c5633938d21d25dd0798ffe3cb1a62b6 to your computer and use it in GitHub Desktop.
Save kgleong/c5633938d21d25dd0798ffe3cb1a62b6 to your computer and use it in GitHub Desktop.
UIViewControllerAnimatedTransitioning
extension MyViewController: UIViewControllerAnimatedTransitioning {
func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return 2.0
}
func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
// Retrieve the view controllers participating in the current transition from the context.
let fromView = transitionContext.viewController(forKey: .from)!.view!
let toView = transitionContext.viewController(forKey: .to)!.view!
// If the view to transition from is this controller's view, the drawer is being presented.
let isPresentingDrawer = fromView == view
let drawerView = isPresentingDrawer ? toView : fromView
if isPresentingDrawer {
// Any presented views must be part of the container view's hierarchy
transitionContext.containerView.addSubview(drawerView)
}
/***** Animation *****/
let drawerSize = CGSize(
width: UIScreen.main.bounds.size.width * 0.5,
height: UIScreen.main.bounds.size.height)
// Determine the drawer frame for both on and off screen positions.
let offScreenDrawerFrame = CGRect(origin: CGPoint(x: drawerSize.width * -1, y:0), size: drawerSize)
let onScreenDrawerFrame = CGRect(origin: .zero, size: drawerSize)
drawerView.frame = isPresentingDrawer ? offScreenDrawerFrame : onScreenDrawerFrame
let animationDuration = transitionDuration(using: transitionContext)
// Animate the drawer sliding in and out.
UIView.animate(withDuration: animationDuration, animations: {
drawerView.frame = isPresentingDrawer ? onScreenDrawerFrame : offScreenDrawerFrame
}, completion: { (success) in
// Cleanup view hierarchy
if !isPresentingDrawer {
drawerView.removeFromSuperview()
}
// IMPORTANT: Notify UIKit that the transition is complete.
transitionContext.completeTransition(success)
})
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment