jsdw_ios/QuickLocation/Component/ImagePicker/PopupAnimator.swift

93 lines
3.2 KiB
Swift

//
// PopupAnimator.swift
// JiuLaiBao
//
// Created by SeanXu on 2018/8/5.
// Copyright © 2018 GuoXiaoMei. All rights reserved.
//
import UIKit
import SnapKit
public protocol PopupViewControllerType {
var grayView: UIView { get set }
var contentView: UIView { get set }
var contentHeight: CGFloat { get set }
}
public enum PopupAnimatorType {
case present
case dismiss
}
public class PopupAnimator: NSObject, UIViewControllerAnimatedTransitioning {
public var animatorType: PopupAnimatorType
public init(_ animatorType: PopupAnimatorType) {
self.animatorType = animatorType
super.init()
}
public func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return 0.3
}
public func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
let containerView = transitionContext.containerView
guard let fromViewController = transitionContext.viewController(forKey: .from),
let toViewController = transitionContext.viewController(forKey: .to),
let fromView = fromViewController.view,
let toView = toViewController.view else {
print("!!! Error: popup animation is not allowed !!!")
return
}
if animatorType == .present {
guard let popup = toViewController as? PopupViewControllerType else {
return
}
let grayView = popup.grayView
let contentView = popup.contentView
let duration = transitionDuration(using: transitionContext)
toView.frame = containerView.frame
containerView.addSubview(toView)
toView.layoutIfNeeded()
grayView.alpha = 0
contentView.snp.updateConstraints { make in
make.bottom.equalToSuperview()
}
toView.setNeedsUpdateConstraints()
UIView.animate(withDuration: duration, delay: 0, options: [.curveEaseInOut], animations: {
toView.layoutIfNeeded()
grayView.alpha = 1.0
}, completion: { _ in
transitionContext.completeTransition(!transitionContext.transitionWasCancelled)
})
} else if animatorType == .dismiss {
guard let popup = fromViewController as? PopupViewControllerType else {
return
}
let grayView = popup.grayView
let contentView = popup.contentView
let contentHeight = popup.contentHeight
let duration = transitionDuration(using: transitionContext)
contentView.snp.updateConstraints { make in
make.bottom.equalTo(contentHeight)
}
fromView.setNeedsUpdateConstraints()
UIView.animate(withDuration: duration, delay: 0, options: [.curveEaseInOut], animations: {
fromView.layoutIfNeeded()
grayView.alpha = 0
}, completion: { _ in
transitionContext.completeTransition(!transitionContext.transitionWasCancelled)
})
}
}
}