//默认的Modal,会将上一级的视图移走
let photoBrowserController = PhotoBrowserController(urls: urls,indexPaht: indexPath)
//指定动画的提供者,transitioningDelegate 隐式动画。
photoBrowserController.transitioningDelegate = self?.photoBrowserAnimator
//指定Model的样式是自定义的
photoBrowserController.modalPresentationStyle = UIModalPresentationStyle.Custom
self?.presentViewController(photoBrowserController,animated: false,completion: nil)
//-----------------------------------------------------定义转场动画类----------------------------------------------------------------------
import UIKit
/// 专门给控制器提供 ‘转场’ 的动画模型 class PhotoBrowserAnimator: NSObject,UIViewControllerTransitioningDelegate { //是否展示动画 var isPresent = false /// 返回提供展现 Presented 转场动画的对象 func animationControllerForPresentedController(presented: UIViewController,presentingController presenting: UIViewController,sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning? { isPresent = true return self } /// 返回消失时 Dismissed 转场动画的对象 func animationControllerForDismissedController(dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? { isPresent = false return self } } extension PhotoBrowserAnimator: UIViewControllerAnimatedTransitioning{ /// '转场'时长 /// /// - parameter transitionContext: transition[转场]Context 上下文 /// /// - returns: 时长 func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval { return 0.5 } /// 实现专场动画效果 - 一旦实现这个方法,必须完成动画效果 /// /// - parameter transitionContext: transition[转场]Context 提供一转场动画效果的一切细节 func animateTransition(transitionContext: UIViewControllerContextTransitioning) { isPresent ? presentAnimation(transitionContext) : dismissAnimation(transitionContext) } /// 消失时动画 /// /// - parameter transitionContext: transitionContext private func dismissAnimation(transitionContext: UIViewControllerContextTransitioning){ let fromView = transitionContext.viewControllerForKey(UITransitionContextFromViewControllerKey)?.view UIView.animateWithDuration(transitionDuration(transitionContext),animations: { () -> Void in fromView?.alpha = 0 }) { (_) -> Void in fromView?.removeFromSuperview() transitionContext.completeTransition(true) } } /// 出现时动画 /// /// - parameter transitionContext: transitionContext private func presentAnimation(transitionContext: UIViewControllerContextTransitioning){ //展示动哈 let toView = transitionContext.viewControllerForKey(UITransitionContextToViewControllerKey)!.view toView.alpha = 0 //获取容器视图 let containerView = transitionContext.containerView() //将视图添加到容器视图上才能看到动画效果 containerView?.addSubview(toView) UIView.animateWithDuration(transitionDuration(transitionContext),animations: { () -> Void in toView.alpha = 0 }) { (_ ) -> Void in //动画完成后要声明方式 transitionContext.completeTransition(true) } } } 原文链接:https://www.f2er.com/swift/325602.html