天天看點

自定義viewController切換動畫

實作效果

系統自帶的viewControll切換動畫有push動畫和模态動畫,一般在正常情況下已經夠用了,但并滿足不了一些複雜的切換效果,比如下圖一些效果github代碼連結:

自定義viewController切換動畫

基本介紹

相關的内容都定義在UIKit的UIViewControllerTransitioning.h中

  • 設定動畫時間
func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval {
        return animationDuration
    }
           
  • 在這裡實作自定義動畫
func animateTransition(transitionContext: UIViewControllerContextTransitioning) {
//動畫之前的視圖
                self.fromVC = transitionContext.viewControllerForKey(UITransitionContextFromViewControllerKey)
                //即将出現的視圖
                self.toVC = transitionContext.viewControllerForKey(UITransitionContextToViewControllerKey)//containerView是容器的view,需要将要出現的view加載上去
                transitionContext.containerView()?.addSubview(self.toVC!.view)
                //添加手勢到即将出現的view上
                self.prepareGestureRecognizerInView(toVC!.view)
                //對動畫之前的視圖進行調整,比如frame
                self.pushBefore()
                //自定義動畫效果
        UIView.animateWithDuration(animationDuration, delay: , options: UIViewAnimationOptions.CurveEaseInOut, animations: { () -> Void in
                self.popAnimation()
            }
            }) { (isCompelete) -> Void in
                if self.isPush
                {
                //完成時調用
                    transitionContext.completeTransition(true)
                }else{
                    transitionContext.completeTransition(!transitionContext.transitionWasCancelled());
                }
        }
}
           
  • 需要實作的代理方法
    //傳回Presented動畫
    func animationControllerForPresentedController(presented: UIViewController, presentingController presenting: UIViewController, sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        self.animation?.isPush = true
        return self.animation
    }
    
    //傳回Dismissed動畫
    func animationControllerForDismissedController(dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        self.animation?.isPush = false
        return self.animation
    }
    
    //傳回push和pop動畫
    func navigationController(navigationController: UINavigationController, animationControllerForOperation operation: UINavigationControllerOperation, fromViewController fromVC: UIViewController, toViewController toVC: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        if operation == UINavigationControllerOperation.Push{
            self.animation!.isPush = true
        }else{
            self.animation!.isPush = false
        }
        return self.animation
    }
               
    具體實作請看代碼