自定义modal动画 by Swift

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


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

gif2
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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 199,711评论 5 468
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 83,932评论 2 376
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 146,770评论 0 330
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 53,799评论 1 271
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 62,697评论 5 359
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,069评论 1 276
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,535评论 3 390
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,200评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,353评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,290评论 2 317
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,331评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,020评论 3 315
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,610评论 3 303
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,694评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,927评论 1 255
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,330评论 2 346
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 41,904评论 2 341

推荐阅读更多精彩内容