Skip to content

Instantly share code, notes, and snippets.

@LeoValentim
Last active August 11, 2017 17:49
Show Gist options
  • Save LeoValentim/19af4414a6475355be97894513ac0d3c to your computer and use it in GitHub Desktop.
Save LeoValentim/19af4414a6475355be97894513ac0d3c to your computer and use it in GitHub Desktop.
Direction Animated Controller
//
// DirectionAnimatedController.swift
//
// Created by Leo Valentim on 17/07/17.
//
import UIKit
enum DirectionAnimation {
case left, right, top, bottom
}
class DirectionAnimatedController: NSObject, UIViewControllerAnimatedTransitioning {
private var direction: DirectionAnimation = .right
public var Direction: DirectionAnimation {
get{
return self.direction
}
set{
self.direction = newValue
}
}
private var duration: TimeInterval = 1.0
public var Duration: TimeInterval {
get{
return self.duration
}
set{
self.duration = newValue
}
}
func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return self.duration
}
func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
let fromViewController = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.from)!
let toViewController = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.to)!
let finalFrameToView = transitionContext.finalFrame(for: toViewController)
var finalFrameFromView = CGRect()
let containerView = transitionContext.containerView
let bounds = UIScreen.main.bounds
switch self.direction {
case .right:
finalFrameFromView = finalFrameToView.offsetBy(dx: -bounds.size.width, dy: 0)
toViewController.view.frame = finalFrameToView.offsetBy(dx: bounds.size.width, dy: 0)
case .left:
finalFrameFromView = finalFrameToView.offsetBy(dx: bounds.size.width, dy: 0)
toViewController.view.frame = finalFrameToView.offsetBy(dx: -bounds.size.width, dy: 0)
case .top:
finalFrameFromView = finalFrameToView.offsetBy(dx: 0, dy: bounds.size.height)
toViewController.view.frame = finalFrameToView.offsetBy(dx: 0, dy: -bounds.size.height)
default:
finalFrameFromView = finalFrameToView.offsetBy(dx: 0, dy: -bounds.size.height)
toViewController.view.frame = finalFrameToView.offsetBy(dx: 0, dy: bounds.size.height)
}
containerView.addSubview(toViewController.view)
UIView.animate(withDuration: transitionDuration(using: transitionContext), delay: 0.0, options: .curveEaseOut, animations: {
toViewController.view.frame = finalFrameToView
fromViewController.view.frame = finalFrameFromView
}, completion: {
finished in
transitionContext.completeTransition(true)
})
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment