自定义modal动画 by Swift

主要内容:实现自定义转场动画


大家平常用微信,微博的过程中肯定都有查看过朋友圈和微博所发布的照片,当点击九宫格的某一图片时图片会慢慢的放大并进入全屏,左右滑动查看另一张.轻点图片又会以动画的方式慢慢缩小回到滑动之后对应的图片.直接上图和代码吧,talk is cheap.
  • 先展示一下效果
gif1

gif2

  • 具体实现步骤

    • 1 .创建两个控制器,一个是HomeViewController(modal之前的控制器),九宫格展示图片列表,另一个是PhotoViewController(之后需要modal出来的控制器),用于展示大图.
    • 2 .自定义一个类(可以定义成工具类,方便复用),需要继承自NSObject并遵守UIViewControllerTransitioningDelegate协议,并且实现该协议中的两个代理方法,目的是为了设置管理显示和消失动画是由哪个控制器管理,isPresented属性用于之后的判断是消失动画还是显示动画.
    class TransionAnimator: NSObject {
    // MARK:- 设置属性
    var isPresented : Bool = false
    var indexPath : NSIndexPath?
    

}
// 设置管理出现动画
func animationControllerForPresentedController(presented: UIViewController, presentingController presenting: UIViewController, sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning?{

    isPresented = true
    return self
}

// 设置管理消失动画
func animationControllerForDismissedController(dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {

    isPresented = false
    return self
}
```

- 3 .在`HomeViewController`中去定义一个属性用来保存转场动画管理者,因为如果该对象被释就无法完成转场动画.并且将这个对象设置成为`PhotoViewController`的`transitioningDelegate`,并且实现`UIViewControllerAnimatedTransitioning`协议中的方法,才能自定义转场动画

  • 4 .来到自定义的动画管理者文件中,实现协议中的方法

    //设置动画持续时间
    public func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval
    //设置具体的动画
    public func animateTransition(transitionContext: UIViewControllerContextTransitioning)
    

  • 5 如何去实现动画:

    • 5.1 考虑到完成显示和消失的动画需要三个值,起始的位置,结束的位置,还有执行动画的占位视图.但是这三个值并不是固定的,需要外界传入.这时就考虑面向协议开发,就像许多第三方框架所做的:只需要调用提供的接口,并传入所需要的接口,
    // 显示动画代理
    

protocol TransitionPresentedProtocol : class {
func getImageView(indexPath : NSIndexPath) -> UIImageView
func getStartRect(indexPath : NSIndexPath) -> CGRect
func getEndRect(indexPath : NSIndexPath) -> CGRect
}
//消失动画代理
protocol TransitionDismissProtocol : class {
func getImageView() -> UIImageView
func getIndexPath() -> NSIndexPath
}

```

 - 5.2 实现代理方法,获得需要的值:

 ```swift
 //实现显示动画代理,获得返回值
 extension HomeViewController : TransitionPresentedProtocol {
func getImageView(indexPath: NSIndexPath) -> UIImageView {
    let imageView = UIImageView()
    let cell = collectionView(collectionView!, cellForItemAtIndexPath: indexPath) as! HomeViewCell
    imageView.image = cell.imageView.image
    imageView.contentMode = .ScaleAspectFill
    imageView.clipsToBounds = true
    return imageView
}
//
func getEndRect(indexPath: NSIndexPath) -> CGRect {
    let cell = collectionView(collectionView!, cellForItemAtIndexPath: indexPath) as! HomeViewCell
    return calculateImageFrame(cell.imageView.image!)
}
func getStartRect(indexPath: NSIndexPath) -> CGRect {
    let cell = collectionView(collectionView!, cellForItemAtIndexPath: indexPath) as! HomeViewCell
    let startRect = collectionView!.convertRect(cell.frame, toView: UIApplication.sharedApplication().keyWindow)
    return startRect
}
 ```

 ```swift
 //实现消失动画代理,获得返回值
extension PhotoViewController : TransitionDismissProtocol {
func getImageView() -> UIImageView {
    let cell = collectionV.visibleCells().first as! PhotoViewCell
    let imageView = cell.imageV
    imageView.contentMode = .ScaleAspectFill
    imageView.clipsToBounds = true
    return imageView
}
func getIndexPath() -> NSIndexPath {
    let cell =  collectionV.visibleCells().first as! PhotoViewCell
    let indexPath = collectionV.indexPathForCell(cell)
    return indexPath!
}
 ```
  - 5.3 实现动画效果

  ```swift

//设置转场动画时长
func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval {
return 2.0
}
//设置转场动画
func animateTransition(transitionContext: UIViewControllerContextTransitioning) {
//设置显示动画
if isPresented {
//0.nil值校验
guard let indexPath = indexPath,presentedDelegate = presentedDelegate else {return}
//1获得弹出的View
let presentedView = transitionContext.viewForKey(UITransitionContextToViewKey)!
//2.获得占位视图
let imageV = presentedDelegate.getImageView(indexPath)
//3.将占位视图添加到containerView上
transitionContext.containerView()?.addSubview(imageV)
//4.设置占位视图的frame
imageV.frame = presentedDelegate.getStartRect(indexPath)
//5.容器视图设置背景色
transitionContext.containerView()?.backgroundColor = UIColor.blackColor()
//6.执行动画
UIView.animateWithDuration(transitionDuration(transitionContext), animations: { () -> Void in
imageV.frame = presentedDelegate.getEndRect(indexPath)
}, completion: { (_) -> Void in
//移除占位视图
imageV.removeFromSuperview()
//将弹出的View加到containerView上
transitionContext.containerView()?.addSubview(presentedView)
//容器视图清除背景色
transitionContext.containerView()?.backgroundColor = UIColor.clearColor()
//设置已完成转场
transitionContext.completeTransition(true)
})

    } else {//设置消失动画
        //0.nil值校验
        guard let presentedDelegate = presentedDelegate , dismissDelegate = dismissDelegate  else {return}
        //1获得即将消失的view
        let dismissView = transitionContext.viewForKey(UITransitionContextFromViewKey)!

        //3.获得占位imageView
        let imageView = dismissDelegate.getImageView()
        //4.将占位视图添加到容器视图上面
        transitionContext.containerView()?.addSubview(imageView)
        //2执行消失动画
        //获得最终的indexPath
        let indexPath = dismissDelegate.getIndexPath()
        //获得之前显示动画的起始位置,
        var endRect = presentedDelegate.getStartRect(indexPath)

        //判断最终消失的位置是否在屏幕之外
        if endRect.origin.y > UIScreen.mainScreen().bounds.height {
            endRect = CGRectZero
        }

        dismissView.alpha = endRect == CGRectZero ? 1.0 : 0.0
        imageView.alpha = 1.0 - dismissView.alpha

        UIView.animateWithDuration(transitionDuration(transitionContext), animations: { () -> Void in
            if endRect == CGRectZero {
                dismissView.alpha = 0.0
            } else {
                imageView.frame = endRect
            }

        }, completion: { (_) -> Void in
                imageView.removeFromSuperview()
                dismissView.removeFromSuperview()
                transitionContext.completeTransition(true)
        })
    }
}
```
- 6 注意事项:

 - 如果在PhotoView里一直向后滑动,那么返回之前的HomeView的时候可能会导致崩溃.这是由于cell的重用机制,只有当cell即将显示出来的时候才会去缓存池中取cell并加载,若HomeView中的cell超出了屏幕的范围,是取不出cell的,从而导致崩溃.那么解决方法可以时主动去调用数据源方法,传入indexPath返回一个cell,再去使用cell里面的数据,或者使用设置offset的方式,滚动到对应位置,就能取出对应的cell了. 我使用的是主动去调用
 - 

![Uploading photo1_989090.gif . . .]transitionContext.containerView,也就是容器层是用来展示最后modal出来的View,要把占位视图和最后modal出来的View添加上去


代码地址

下载之后pod install,打开.xcworkspace就能运行
https://git.coding.net/DHai/PhotoViewer-Swift.git

你可能感兴趣的:(自定义modal动画 by Swift)