SheetController/Sources/SheetController/SheetContainerDismissAnimat...

60 lines
2.2 KiB
Swift

//
// SheetContainerDismissAnimationController.swift
// SheetController
//
// Created by Shadowfacts on 9/24/19.
// Copyright © 2019 Shadowfacts. All rights reserved.
//
import UIKit
class SheetContainerDismissAnimationController: NSObject, UIViewControllerAnimatedTransitioning {
func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return 0.35
}
func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
guard let fromVC = transitionContext.viewController(forKey: .from) as? SheetContainerViewController else {
fatalError()
}
fromVC.view.alpha = 1.0
fromVC.dimmingView.isHidden = true
// match the frame to the original dimming view's frame so that it doesn't go under the content
let dimmingView = UIView(frame: fromVC.dimmingView.bounds)
dimmingView.backgroundColor = fromVC.dimmingView.backgroundColor
dimmingView.alpha = fromVC.dimmingView.alpha
let container = transitionContext.containerView
container.addSubview(dimmingView)
container.addSubview(fromVC.view)
let duration = transitionDuration(using: transitionContext)
let animator: UIViewPropertyAnimator
if let initialVelocity = fromVC.dismissAnimationInitialVelocity {
let vector = CGVector(dx: initialVelocity, dy: 0)
let parameters = UISpringTimingParameters(dampingRatio: 1, initialVelocity: vector)
animator = UIViewPropertyAnimator(duration: duration, timingParameters: parameters)
} else {
animator = UIViewPropertyAnimator(duration: duration, curve: .easeOut)
}
animator.addAnimations {
dimmingView.frame = container.bounds
dimmingView.alpha = 0
fromVC.view.transform = CGAffineTransform(translationX: 0, y: fromVC.content.view.bounds.height)
}
animator.addCompletion { (position) in
dimmingView.removeFromSuperview()
transitionContext.completeTransition(!transitionContext.transitionWasCancelled)
}
animator.startAnimation()
}
}