Last active
May 11, 2017 15:25
-
-
Save kmikael/75c1519cd5d97a924cc86646542fd2bb to your computer and use it in GitHub Desktop.
[WIP] Creating a Custom Presentation Transition
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// https://developer.apple.com/reference/uikit/uiviewcontrollertransitioningdelegate | |
class AnimationController: NSObject, UIViewControllerAnimatedTransitioning { | |
func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval { | |
return 0.2 // The duration of the animation | |
} | |
func animateTransition(using transitionContext: UIViewControllerContextTransitioning) { | |
// Since you are presenting a new view controller, you primarily need the new view controller | |
guard let toViewController = transitionContext.viewController(forKey: .to) else { | |
return | |
} | |
// At the end of this method, this needs to be set. | |
// You place the new view controller's view at it's final frame | |
// Since you will be using a transform below, you can just do it now. | |
toViewController.view.frame = transitionContext.finalFrame(for: toViewController) | |
// You also need to add the new view controller's view to the container view | |
// At the latest before you call completeTransition() | |
transitionContext.containerView.addSubview(toViewController.view) | |
// Since you only have one anmination in most cases, you can use the complete duration for the animation duration | |
let duration = transitionDuration(using: transitionContext) | |
// It's almost time, hide the new view and transform it | |
toViewController.view.alpha = 0.0 | |
toViewController.view.transform = CGAffineTransform(scaleX: 0.001, y: 0.001) | |
// Warning If you attempt to set the frame of the new view controller, things will get messeed up | |
// as the subviews will get scrambled, in this case you might need a snapshot view | |
let animations = { | |
// Set all of the new view's properties back to normal | |
toViewController.view.alpha = 1.0 | |
toViewController.view.transform = .identity | |
} | |
let completion = { (finished: Bool) in | |
// You must call this, otherwise iOS will not clear the many transitioning views | |
// and your new view contrroller will be unresponsive | |
transitionContext.completeTransition(finished) | |
} | |
// Animate and you're done | |
UIView.animate(withDuration: duration, animations: animations, completion: completio | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment