Open a View Controller with animation - ios

I would like to open a View Controller with an animation with the origin Frame of a square button on the bottom right:
I would like to move the top and then the bottom of the View Controller.
I tried to implement this, but that is not that good, I don't know how I can isolate the different edges:
class PopAnimator: NSObject, UIViewControllerAnimatedTransitioning {
let duration = 0.6
var presenting = true
var originFrame = CGRect.zero
func transitionDuration(transitionContext: UIViewControllerContextTransitioning?)-> NSTimeInterval {
return duration
}
func animateTransition(transitionContext: UIViewControllerContextTransitioning) {
let containerView = transitionContext.containerView()!
let toView = transitionContext.viewForKey(UITransitionContextToViewKey)!
let herbView = presenting ? toView : transitionContext.viewForKey(UITransitionContextFromViewKey)!
let initialFrame = presenting ? originFrame : herbView.frame
let finalFrame = presenting ? herbView.frame : originFrame
let xScaleFactor = presenting ?
initialFrame.width / finalFrame.width :
finalFrame.width / initialFrame.width
let yScaleFactor = presenting ?
initialFrame.height / finalFrame.height :
finalFrame.height / initialFrame.height
let scaleTransform = CGAffineTransformMakeScale(xScaleFactor, yScaleFactor)
if presenting {
herbView.transform = scaleTransform
herbView.center = CGPoint(
x: CGRectGetMidX(initialFrame),
y: CGRectGetMidY(initialFrame))
herbView.clipsToBounds = true
}
containerView.addSubview(toView)
containerView.bringSubviewToFront(herbView)
UIView.animateWithDuration(duration, delay:0.0,
options: [],
animations: {
herbView.transform = self.presenting ?
CGAffineTransformIdentity : scaleTransform
herbView.center = CGPoint(x: CGRectGetMidX(finalFrame),
y: CGRectGetMidY(finalFrame))
}, completion:{_ in
transitionContext.completeTransition(true)
})
let round = CABasicAnimation(keyPath: "cornerRadius")
round.fromValue = presenting ? 3.0/xScaleFactor : 0.0
round.toValue = presenting ? 0.0 : 3.0/xScaleFactor
round.duration = duration / 2
herbView.layer.addAnimation(round, forKey: nil)
herbView.layer.cornerRadius = presenting ? 0.0 : 3.0/xScaleFactor
}
}
Do you know how I can make it ?

Related

How to make transition of a ViewController from Bottom to Top?

So here is a class for Slide in transition which adds a ViewController with animation from left to right and it works flawlessly I want a transition from bottom to top.
import UIKit
class SlideInTransition: NSObject, UIViewControllerAnimatedTransitioning {
var isPresenting = false
let dimmingView = UIView()
func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return 0.3
}
func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
guard let toViewController = transitionContext.viewController(forKey: .to),
let fromViewController = transitionContext.viewController(forKey: .from) else { return }
let containerView = transitionContext.containerView
let finalWidth = toViewController.view.bounds.width * 0.8
let finalHeight = toViewController.view.bounds.height
if isPresenting {
// Add dimming view
dimmingView.backgroundColor = .black
dimmingView.alpha = 0.0
containerView.addSubview(dimmingView)
dimmingView.frame = containerView.bounds
// Add menu view controller to container
containerView.addSubview(toViewController.view)
// Init frame off the screen
toViewController.view.frame = CGRect(x: -finalWidth, y: 0, width: finalWidth, height: finalHeight)
}
// Move on screen
let transform = {
self.dimmingView.alpha = 0.5
toViewController.view.transform = CGAffineTransform(translationX: finalWidth, y: 0)
}
// Move back off screen
let identity = {
self.dimmingView.alpha = 0.0
fromViewController.view.transform = .identity
}
// Animation of the transition
let duration = transitionDuration(using: transitionContext)
let isCancelled = transitionContext.transitionWasCancelled
UIView.animate(withDuration: duration, animations: {
self.isPresenting ? transform() : identity()
}) { (_) in
transitionContext.completeTransition(!isCancelled)
}
}
}
To be honest I copied this code from somewhere a while ago and I don't have a source of it.
I'm fairly new to iOS so any help would be appreciated.
Try this,
class SlideInTransition: NSObject, UIViewControllerAnimatedTransitioning {
var isPresenting = false
let dimmingView = UIView()
func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return 0.3
}
func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
guard let toViewController = transitionContext.viewController(forKey: .to),
let fromViewController = transitionContext.viewController(forKey: .from) else { return }
let containerView = transitionContext.containerView
let finalWidth = toViewController.view.bounds.width
let finalHeight = toViewController.view.bounds.height * 0.8
if isPresenting {
// Add dimming view
dimmingView.backgroundColor = .black
dimmingView.alpha = 0.0
containerView.addSubview(dimmingView)
dimmingView.frame = containerView.bounds
// Add menu view controller to container
containerView.addSubview(toViewController.view)
// Init frame off the screen
toViewController.view.frame = CGRect(x: 0, y: finalHeight, width: finalWidth, height: finalHeight)
}
// Move on screen
let transform = {
self.dimmingView.alpha = 0.5
toViewController.view.transform = CGAffineTransform(translationX: 0, y: -finalHeight)
}
// Move back off screen
let identity = {
self.dimmingView.alpha = 0.0
fromViewController.view.transform = .identity
}
// Animation of the transition
let duration = transitionDuration(using: transitionContext)
let isCancelled = transitionContext.transitionWasCancelled
UIView.animate(withDuration: duration, animations: {
self.isPresenting ? transform() : identity()
}) { (_) in
transitionContext.completeTransition(!isCancelled)
}
}
}

Custom Presentation transition broke on iOS13

I have this CollectionView with small images and a UIViewController with single image on the center of a screen with full-screen width.
When user taps on small image it should scale to take full screen width.
There's a custom transition animation between those two.
let previewVC = PreviewTutorialViewController(image: image!, imageFrame: frame, text: data!.text, imageView: cell.toDoImageView)
previewVC.modalPresentationStyle = .overCurrentContext
previewVC.transitioningDelegate = previewVC
self.present(previewVC, animated: true, completion: nil)
AnimationController
class AnimationController: NSObject, UIViewControllerAnimatedTransitioning {
var duration = 10.4
var isPresenting: Bool
init(forTransitionType type: TransitionType) {
self.isPresenting = type == .presenting
super.init()
}
func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return self.duration
}
func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
let containerView = transitionContext.containerView
let fromVC = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.from)!
let toVC = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.to)!
var imageRectAfter : CGRect = .zero
var imageRectInitial : CGRect = .zero
var previewTutorialVC : PreviewTutorialViewController?
if self.isPresenting {
containerView.addSubview(toVC.view)
containerView.layoutIfNeeded()
previewTutorialVC = (toVC as! PreviewTutorialViewController)
imageRectInitial = previewTutorialVC!.initialRect
imageRectAfter = previewTutorialVC!.tutorialImageView.frame
previewTutorialVC?.initialImageView?.alpha = 0
print("$$$ animating image view frame : PRESENTING ", imageRectInitial, " to ", imageRectAfter)
} else {
previewTutorialVC = (fromVC as! PreviewTutorialViewController)
imageRectAfter = previewTutorialVC!.initialRect
imageRectInitial = previewTutorialVC!.tutorialImageView.frame
print("$$$ animating image view frame : DISSMISSING ", imageRectInitial, " to ", imageRectAfter)
//let frame2 = previewTutorialVC!.tutorialImageView.convert(imageRectInitial, to: containerView)
//imageRectInitial = CGRect(x: 0, y: 430, width: 414, height: 155)
//print("$$$ converted :", frame2)
print("$$$ ", containerView.bounds.size.width, previewTutorialVC?.view.bounds.size.width)
}
previewTutorialVC?.tutorialImageView.transform = .identity
previewTutorialVC?.tutorialImageView.frame = imageRectInitial
previewTutorialVC?.containerView.alpha = isPresenting == true ? 0 : 1
previewTutorialVC?.closeButton.alpha = self.isPresenting == true ? 0 : 1
//previewTutorialVC?.textContainerView.transform = isPresenting == true ? CGAffineTransform(translationX: 0, y: previewTutorialVC?.textContainerView.frame.size.height ?? 0) : .identity
UIView.animate(withDuration: duration, delay: 0, options: [.curveEaseOut], animations: {
previewTutorialVC?.tutorialImageView.frame = imageRectAfter
previewTutorialVC?.containerView.alpha = self.isPresenting == true ? 1 : 0
previewTutorialVC?.closeButton.alpha = self.isPresenting == true ? 1 : 0
// previewTutorialVC?.textContainerView.transform = self.isPresenting == true ? .identity : CGAffineTransform(translationX: 0, y: previewTutorialVC?.textContainerView.frame.size.height ?? 0)
}) { (_) in
if self.isPresenting == false { previewTutorialVC?.initialImageView?.alpha = 1 }
transitionContext.completeTransition(!transitionContext.transitionWasCancelled)
}
}
}
Console log:
$$$ animating image view frame : PRESENTING (15.0, 461.5, 384.0, 143.5) to (0.0, 370.5, 414.0, 155.0)
$$$ animating image view frame : DISSMISSING (0.0, 370.5, 414.0, 155.0) to (15.0, 461.5, 384.0, 143.5)
It used to work fine, but since iOS 13 i've noticed dismiss animation starts with way too wide image than it should be, although frame prints correct values.. also dismiss animation ends with image being a bit too high. Present animation's working fine
previewTutorialVC?.tutorialImageView.translatesAutoresizingMaskIntoConstraints = true
this inside dismiss block fixed the issue. As mentioned here

Present UIViewController from frame

I am showing image slider as in this order.
UIViewController > UITableview > UITableviewCell > UICollectionview > UICollectionViewCell > UIImage
User can slide UICollectionview and view images.Problem is that I need to do animation. When user tap on my UICollectionviewCell, it should animate from that cell and show full screen as in this library.
https://github.com/suzuki-0000/SKPhotoBrowser
Problem is that I need to use MWPhotoBrowser and I can't present like that.
I am thinking to use hero animation library as well.
https://github.com/lkzhao/Hero
But my view hierachy and their example is different. How shall I do?
You have to use custom transition
Reference:
https://developer.apple.com/library/content/featuredarticles/ViewControllerPGforiPhoneOS/CustomizingtheTransitionAnimations.html
Code Work
On image selection
add in VC_A
var selectedImage: UIImageView?
let transition = PopAnimator()
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransition(to: size, with: coordinator)
coordinator.animate(
alongsideTransition: {context in
self.bgImage.alpha = (size.width>size.height) ? 0.25 : 0.55
self.positionListItems()
},
completion: nil
)
}
//position all images inside the list
func positionListItems() {
let listHeight = listView.frame.height
let itemHeight: CGFloat = listHeight * 1.33
let aspectRatio = UIScreen.main.bounds.height / UIScreen.main.bounds.width
let itemWidth: CGFloat = itemHeight / aspectRatio
let horizontalPadding: CGFloat = 10.0
for i in herbs.indices {
let imageView = listView.viewWithTag(i) as! UIImageView
imageView.frame = CGRect(
x: CGFloat(i) * itemWidth + CGFloat(i+1) * horizontalPadding, y: 0.0,
width: itemWidth, height: itemHeight)
}
listView.contentSize = CGSize(
width: CGFloat(herbs.count) * (itemWidth + horizontalPadding) + horizontalPadding,
height: 0)
}
// On image selection
VC_B.transitioningDelegate = self
present(VC_B, animated: true, completion: nil)
// add extension
extension VC_A: UIViewControllerTransitioningDelegate {
func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
transition.originFrame = selectedImage!.superview!.convert(selectedImage!.frame, to: nil)
transition.presenting = true
selectedImage!.isHidden = true
return transition
}
func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
transition.presenting = false
return transition
}
}
and animation class
class PopAnimator: NSObject, UIViewControllerAnimatedTransitioning {
let duration = 1.0
var presenting = true
var originFrame = CGRect.zero
var dismissCompletion: (()->Void)?
func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return duration
}
func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
let containerView = transitionContext.containerView
let toView = transitionContext.view(forKey: .to)!
let herbView = presenting ? toView : transitionContext.view(forKey: .from)!
let initialFrame = presenting ? originFrame : herbView.frame
let finalFrame = presenting ? herbView.frame : originFrame
let xScaleFactor = presenting ?
initialFrame.width / finalFrame.width :
finalFrame.width / initialFrame.width
let yScaleFactor = presenting ?
initialFrame.height / finalFrame.height :
finalFrame.height / initialFrame.height
let scaleTransform = CGAffineTransform(scaleX: xScaleFactor, y: yScaleFactor)
if presenting {
herbView.transform = scaleTransform
herbView.center = CGPoint(
x: initialFrame.midX,
y: initialFrame.midY)
herbView.clipsToBounds = true
}
containerView.addSubview(toView)
containerView.bringSubview(toFront: herbView)
UIView.animate(withDuration: duration, delay:0.0, usingSpringWithDamping: 0.4,
initialSpringVelocity: 0.0,
animations: {
herbView.transform = self.presenting ?
CGAffineTransform.identity : scaleTransform
herbView.center = CGPoint(x: finalFrame.midX,
y: finalFrame.midY)
},
completion:{_ in
if !self.presenting {
self.dismissCompletion?()
}
transitionContext.completeTransition(true)
}
)
}
}

3D Flip Animation for View Controllers in swift

I am trying to get 3d flip animations among view controllers like this
https://github.com/nicklockwood/CubeController
For the animation.. basing on reverse value I set clock wise direction or anti clock direction
This is the code I am using for animation..
class CusNavAnimController : NSObject, UIViewControllerAnimatedTransitioning {
var reverse: Bool = false
func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval {
return 0.25
}
func animateTransition(transitionContext: UIViewControllerContextTransitioning) {
let containerView = transitionContext.containerView()
let toViewController = transitionContext.viewControllerForKey(UITransitionContextToViewControllerKey)!
let fromViewController = transitionContext.viewControllerForKey(UITransitionContextFromViewControllerKey)!
let toView = toViewController.view
let fromView = fromViewController.view
//
toView.frame = UIScreen.mainScreen().bounds
fromView.frame = UIScreen.mainScreen().bounds
let direction: CGFloat = reverse ? -1 : 1
let const: CGFloat = -0.005
toView.layer.anchorPoint = CGPointMake(direction == 1 ? 0 : 1, 0.5)
fromView.layer.anchorPoint = CGPointMake(direction == 1 ? 1 : 0, 0.5)
var viewFromTransform: CATransform3D = CATransform3DMakeRotation(direction * CGFloat(M_PI_2), 0.0, 1.0, 0.0)
var viewToTransform: CATransform3D = CATransform3DMakeRotation(-direction * CGFloat(M_PI_2), 0.0, 1.0, 0.0)
viewFromTransform.m34 = const
viewToTransform.m34 = const
containerView!.transform = CGAffineTransformMakeTranslation(direction * containerView!.frame.size.width / 2.0, 0)
toView.layer.transform = viewToTransform
containerView!.addSubview(toView)
UIView.animateWithDuration(transitionDuration(transitionContext), animations: {
containerView!.transform = CGAffineTransformMakeTranslation(-direction * containerView!.frame.size.width / 2.0, 0)
fromView.layer.transform = viewFromTransform
toView.layer.transform = CATransform3DIdentity
}, completion: {
finished in
containerView!.transform = CGAffineTransformIdentity
fromView.layer.transform = CATransform3DIdentity
toView.layer.transform = CATransform3DIdentity
fromView.layer.anchorPoint = CGPointMake(0.5, 0.5)
toView.layer.anchorPoint = CGPointMake(0.5, 0.5)
if (transitionContext.transitionWasCancelled()) {
toView.removeFromSuperview()
} else {
fromView.removeFromSuperview()
}
transitionContext.completeTransition(!transitionContext.transitionWasCancelled())
})
}}
I am getting the animation but It is not same as the git hub link providing..
For my code.. the fromview is slightly going back and toview coming to front from that point.. can anyone suggest me the changes
Check out TransitionFlipFromLeft and TransitionFlipFromRight in UIViewAnimationOptions

How to make a custom transition behave like a fall under the gravity?

The effect could be implemented like the following code in animateTransition method:
UIView.animateWithDuration(duration,
delay: 0,
usingSpringWithDamping: 0.3,
initialSpringVelocity: 0.0,
options: .CurveLinear,
animations: {
fromVC.view.alpha = 0.5
toVC.view.frame = finalFrame
},
completion: {_ -> () in
fromVC.view.alpha = 1.0
transitionContext.completeTransition(true)
})
But how could I implement it using gravity and collision behaviors(UIGravityBehavior, UICollisionBehavior)?
And a more general question may be "How to use the UIDynamicAnimator to customize the transitions between UIViewControllers?"
You can find the solution under the post Custom view controller transitions with UIDynamic behaviors by dasdom.
And the Swift code:
func transitionDuration(transitionContext: UIViewControllerContextTransitioning!) -> NSTimeInterval {
return 1.0
}
func animateTransition(transitionContext: UIViewControllerContextTransitioning!) {
// 1. Prepare for the required components
let toVC = transitionContext.viewControllerForKey(UITransitionContextToViewControllerKey)
let finalFrame = transitionContext.finalFrameForViewController(toVC)
let containerView = transitionContext.containerView()
let screenBounds = UIScreen.mainScreen().bounds
// 2. Make toVC at the top of the screen
toVC.view.frame = CGRectOffset(finalFrame, 0, -1.0 * CGRectGetHeight(screenBounds))
containerView.addSubview(toVC.view)
// 3. Set the dynamic animators used by the view controller presentation
var animator: UIDynamicAnimator? = UIDynamicAnimator(referenceView: containerView)
let gravity = UIGravityBehavior(items: [toVC.view])
gravity.magnitude = 10
let collision = UICollisionBehavior(items: [toVC.view])
collision.addBoundaryWithIdentifier("GravityBoundary",
fromPoint: CGPoint(x: 0, y: screenBounds.height),
toPoint: CGPoint(x: screenBounds.width, y: screenBounds.height))
let animatorItem = UIDynamicItemBehavior(items: [toVC.view])
animatorItem.elasticity = 0.5
animator!.addBehavior(gravity)
animator!.addBehavior(collision)
animator!.addBehavior(animatorItem)
// 4. Complete the transition after the time of the duration
let nsecs = transitionDuration(transitionContext) * Double(NSEC_PER_SEC)
let delay = dispatch_time(DISPATCH_TIME_NOW, Int64(nsecs))
dispatch_after(delay, dispatch_get_main_queue()) {
animator = nil
transitionContext.completeTransition(true)
}
}
A little more complicated than using animateWithDuration:delay:usingSpringWithDamping:initialSpringVelocity:options:animations:completion: method.
EDIT: Fixed a bug when 'transitionDuration' is ≤1

Resources