自定义 push 和 pop 实现相册翻开效果(下)

话接上篇,实现使用 pinch 手势来控制 push 和 pop。这个下篇相对上篇没有那么难啃。

交互动画条件

从上一篇可知,实现可交互的 push 和 pop 动画还需要提供交互控制器 Interaction Controller,其遵守UIViewControllerInteractiveTransitioning协议,不过这个协议其实没什么用。

看下图:


自定义 push 和 pop 实现相册翻开效果(下)_第1张图片

交互控制器与动画控制器的协作过程如下,动画控制器在其- animateTransition:中必须使用 UIView Animation 来实现需要的动画,这也是上篇中不使用 Core Animation 的原因;然后交互控制器根据外部驱动如手势控制或是其他事件来更新动画的进度。注意:没有动画控制器的情况下交互控制器是无法工作的。

话虽如此,令人惊喜的是在自定义 transition 过程中的发生的所有动画,不限于- animateTransition:里提交的动画,都可以实现交互控制,而且 Core Animation 也支持。但为何苹果的工程师说必须使用 UIView Animation 呢?交互动画可以中断,当外界的驱动比如手势取消或是在某个阶段中断的话,后续的处理一般是根据进度来决定动画继续完成或是取消;而使用而 Core Animation 时,手势中止时,动画将停在当前位置。前面说到,没有放在- animateTransition:的动画也可以实现交互控制,比如你可能会在viewWillDisappear:里执行 UIView Animation,当手势中止时,视图会从当前状态直接跳到动画的最终值。另外,经尝试发现,交互动画只支持UIView block animation 的第一层次,completion Block 中添加的动画会在第一层次的动画结束后正常进行,但不能被交互控制器控制。所以,要想实现交互控制,老老实实把所有的动画都放在动画控制器的- animateTransition:里,而且要用 UIView Animation 实现。

UIViewControllerInteractiveTransitioning协议中的方法对于实现交互动画几乎没什么用处,好在系统已经给我们打包好了一个交互控制器UIPercentDrivenInteractiveTransition,大部分的情况下我们使用这个类就足够了。该类提供了以下几个方法来控制交互的进度:

- updateInteractiveTransition://更新动画的进度
– cancelInteractiveTransition  //取消交互,动画回放至开始时的状态
– finishInteractiveTransition   //完成转场,动画继续直至 push 或 pop 完成

通过这三个方法,交互控制器就像一个视频播放器将 push 或 pop 过程中发生的所有动画当做一部影片来播放。外部的驱动比如手势用来控制影片的播放进度;当手势结束或取消时,可以设定影片继续播放直至结束或是返回至影片开始时。

手势驱动交互

回到SDENavigationControllerDelegate类里,实现下面的可选方法来提供交互控制器:

var interactive = false
private (set) var interactionController: UIPercentDrivenInteractiveTransition?

func navigationController(navigationController: UINavigationController, interactionControllerForAnimationController animationController: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? {
    // 只可以在 pinch 绑定的方法里才能修改这个属性
    if interactive{
        return interactionController
    }

    return nil
}

这里添加了一个interactive属性来标记是否当前动画是否处于交互控制中,这是因为 pop 的动作还可以使用 navigationbar 上的 Back ButtomItem 来完成,此时若还提供交互控制器的话,会造成 pop transition 过程无法结束。不过你重写相关方法,并使用finishInteractiveTransition来结束转场动画也是可以的。

接下来添加 pinch 手势支持。对于 pop 过程,我在默认分支里实现了自动添加 pinch 手势用于 pop;而对于 push 过程,需要创建新的控制器,而使用者的类未知,而且可能需要其他的初始化设置,因此无法实现自动支持,这也是为什么很多库只能自动添加 pop 支持的缘故。而你需要 pinch 同时支持 push 和 pop 时,自动支持 pop 的机制就不能使用了。

使用 pinch 支持 push 和 pop 操作,首先在SDENavigationControllerDelegate里,添加isPush属性用于在使用手势的过程中判断当前是在进行哪种操作:

var isPush = false
func navigationController(navigationController: UINavigationController, animationControllerForOperation operation: UINavigationControllerOperation, fromViewController fromVC: UIViewController, toViewController toVC: UIViewController) -> UIViewControllerAnimatedTransitioning? {
    animationController = SDEPushAndPopAnimationController(operation: operation)
    isPush = (operation == .Push)
    return animationController
}

UICollectionViewController类里添加下面的属性和方法:

var transitionDelegate: SDENavigationControllerDelegate?
var pinchGestureRecognizer: UIPinchGestureRecognizer?{
    didSet(newValue){
        collectionView?.addGestureRecognizer(pinchGestureRecognizer!)
    }
}

override func viewDidLoad() {
    super.viewDidLoad()
    pinchGestureRecognizer = UIPinchGestureRecognizer(target: self, action: "handlePinch:")
}

func getIndexPathForGesture(gesture: UIPinchGestureRecognizer) -> NSIndexPath?{
    let location0 = gesture.locationOfTouch(0, inView: gesture.view)
    let location1 = gesture.locationOfTouch(1, inView: gesture.view)
    let middleLocation = CGPointMake((location0.x + location1.x)/2, (location0.y + location1.y)/2)
    let indexPath = collectionView?.indexPathForItemAtPoint(middleLocation)
    return indexPath
}

func handlePinch(gesture: UIPinchGestureRecognizer){
    switch gesture.state{
    case .Began:
        //设定 pinch 起始向外扩展时实现 push
        if gesture.scale >= 1.0{
            guard let indexPath = getIndexPathForGesture(gesture) else{
                return
            }
            //保存封面索引位置
            self.selectedIndexPath = indexPath

            if let toVC = storyboard?.instantiateViewControllerWithIdentifier("XXX"){
                transitionDelegate = navigationController?.delegate as? SDENavigationControllerDelegate
                transitionDelegate?.interactive = true//只在手势里标记为 true,要求提供交互控制器
                navigationController?.pushViewController(toVC, animated: true)
            }
        }else{
            //如果是向内收缩则实现 pop
            //ViewController 被 pop 后,此时已经被移除出 navigation controller 的栈,通过 self.navigationController 返回的只是 nil,因为必须在 pop 前获取 navigation controller delegate.
            transitionDelegate = self.navigationController?.delegate as? SDENavigationControllerDelegate
            transitionDelegate?.interactive = true//只在手势里标记为 true,要求提供交互控制器
            self.navigationController?.popViewControllerAnimated(true)
        }
    case .Changed:
        guard transitionDelegate != nil else{
            return
        }
        guard let interactionController = transitionDelegate?.interactionController else{
            return
        }
        var progress = gesture.scale
        if transitionDelegate!.isPush{
            progress = gesture.scale - 1.0 >= 0.9 ? 0.9 : gesture.scale - 1.0
        }else{
            progress = 1.0 - gesture.scale
        }
        //根据手势的扩张程度来更新动画进度
        interactionController.updateInteractiveTransition(progress)
    case .Ended, .Cancelled:
        guard transitionDelegate != nil else{
            return
        }
        guard let interactionController = transitionDelegate?.interactionController else{
            return
        }

        var progress = gesture.scale
        if transitionDelegate!.isPush{
            progress = gesture.scale - 1.0 >= 0.9 ? 0.9 : gesture.scale - 1.0
        }else{
            progress = 1.0 - gesture.scale
        }
        //设定一个阈值,用来决定手势停止或取消时是完成交互还是取消交互
        if progress >= 0.4{
            interactionController.finishInteractiveTransition()
        }else{
            interactionController.cancelInteractiveTransition()
        }
        //确保只在使用 pinch 手势时才提供动画的交互
        transitionDelegate?.interactive = false
    default:
        guard transitionDelegate != nil else{
            return
        }
        transitionDelegate?.interactive = false
    }
}

可以看出,虽然代码太长的,但交互动画的实现还是很简单的。当然,这个前提是上篇里实现过场动画时严格按照苹果工程师说的那样使用 UIView Animation 来实现动画,而且必须在动画控制器里的- animateTransition:里面提交动画。

自动支持 pinch for pop

从使用角度讲,使用 pinch 来 push 的操作是很不直观的,除非界面没有给你提供其他选择,不过顶多不给你提供 NavigationBar,不能通过点击而是通过 pinch 手势进入下一级界面的设计显然是脑残行为。通过 pinch 来实现 pop 在如今无疑是个很自然的行为,如何实现自动添加 pinch 手势来支持 pop 呢?显然,要自动添加,我们就不能在UICollectionViewController里动手脚。在执行了navigationController?.pushViewController(toVC, animated: true)这条命令后,系统就会向navigationController的代理询问动画控制器和交互控制器,那么询问动画控制器时就是搞小动作的地方:

private (set) var interactionController: UIPercentDrivenInteractiveTransition?
func navigationController(navigationController: UINavigationController, animationControllerForOperation operation: UINavigationControllerOperation, fromViewController fromVC: UIViewController, toViewController toVC: UIViewController) -> UIViewControllerAnimatedTransitioning? {
    animationController = SDEPushAndPopAnimationController(operation: operation)
    if operation == .Push{
        if let toCollectionVC = toVC as? UICollectionViewController{
            interactionController =  SDEPopPinchInteractionController(toVC: toCollectionVC, holder: self)
        }
    }
    return animationController
}

新的交互控制器在初始化的时候在 toVC 上添加 pinch 手势,注意避免引用循环:

import UIKit

class SDEPopPinchInteractionController: UIPercentDrivenInteractiveTransition {
    private var pinchGesture = UIPinchGestureRecognizer()
    private var topVC: UICollectionViewController
    private unowned var holder: SDENavigationControllerDelegate

    init(toVC topVC: UICollectionViewController, holder: SDENavigationControllerDelegate) {
        self.topVC = topVC
        self.holder = holder
        super.init()
        addPinchGestureOnView(self.topVC.view)
    }

    private func addPinchGestureOnView(view: UIView){
        pinchGesture.addTarget(self, action: "sde_handlePinch:")
        view.addGestureRecognizer(pinchGesture)
    }

    internal func sde_handlePinch(gesture: UIPinchGestureRecognizer){
        switch gesture.state{
        case .Began:
            if gesture.scale < 1.0{
                holder.interactive = true
                topVC.navigationController?.popViewControllerAnimated(true)
            }
        case .Changed:
            if gesture.scale < 1.0{
                let progress = 1.0 - gesture.scale
                self.updateInteractiveTransition(progress)
            }
        case .Ended:
            if gesture.scale < 1.0{
                let progress = 1.0 - gesture.scale
                if progress > 0.4{
                    self.finishInteractiveTransition()
                }else{
                    self.cancelInteractiveTransition()
                }
                holder.interactive = false
            }
        default:
            holder.interactive = false
        }
    }

    deinit{
        pinchGesture.view?.removeGestureRecognizer(pinchGesture)
    }
}

注意,由于 push 操作的特殊性,无法自动添加 pinch 手势来支持 push 操作,如果你需要同时支持两种操作,那么最好放弃自动添加 pinch 支持 pop 的方式,因为一种手势不能添加两种方法。也许你可能尝试下,在 view 里添加 pinch 手势用于 pop,在 collectionView 里添加 pinch 里用于 push,限制只能有一个起作用,似乎行不通,不过你可以试试。

我在 Demo 里实现了上述两种模式:默认分支自动添加 pinch 实现 pop,手动添加 pinch 同时支持 push 和 pop。

后记:

objectivetoast.com 的《Custom Transitions on iOS》是我见过最好的关于 Custom Transition 的文章,甚至 objcc.io 上的两篇关于 Custom Transition 的文章也不如这篇浅显易懂,但是其随后的一篇《Interactive Transition》写得晦涩难懂,主要是作者的示例可以无限制地 push, 为此作者将 AnimationController、InteractiveController 和 NavigationControllerDelegate 都封装了起来了,但是却搞得过于复杂,不是个好的入门例子。

参考资料:
1.View Controller 转场
2.Interactive Transition

你可能感兴趣的:(自定义 push 和 pop 实现相册翻开效果(下))