關(guān)于自定義轉(zhuǎn)場動(dòng)畫,我都告訴你。

概述

這篇文章,我將講述幾種轉(zhuǎn)場動(dòng)畫的自定義方式,并且每種方式附上一個(gè)示例,畢竟代碼才是我們的語言,這樣比較容易上手。其中主要有以下三種自定義方法,供大家參考:

  • Push & Pop
  • Modal
  • Segue

前兩種大家都很熟悉,第三種是 Stroyboard 中的拖線,屬于 UIStoryboardSegue 類,通過繼承這個(gè)類來自定義轉(zhuǎn)場過程動(dòng)畫。

Push & Pop

首先說一下 Push & Pop 這種轉(zhuǎn)場的自定義,操作步驟如下:

  1. 創(chuàng)建一個(gè)文件繼承自 NSObject, 并遵守 UIViewControllerAnimatedTransitioning協(xié)議。

  2. 實(shí)現(xiàn)該協(xié)議的兩個(gè)基本方法:

    //指定轉(zhuǎn)場動(dòng)畫持續(xù)的時(shí)長
    func transitionDuration(transitionContext: UIViewControllerContextTransitioning) -> NSTimeInterval      
    //轉(zhuǎn)場動(dòng)畫的具體內(nèi)容       
    func animateTransition(transitionContext: UIViewControllerContextTransitioning)
    
  3. 遵守 UINavigationControllerDelegate 協(xié)議,并實(shí)現(xiàn)此方法:

    func navigationController(navigationController: UINavigationController, animationControllerForOperation operation: UINavigationControllerOperation, fromViewController fromVC: UIViewController, toViewController toVC: UIViewController) -> UIViewControllerAnimatedTransitioning?
    

    在此方法中指定所用的 UIViewControllerAnimatedTransitioning,即返回 第1步 中創(chuàng)建的類。

    注意:由于需要 PushPop,所以需要兩套動(dòng)畫方案。解決方法為:

    第1步 中,創(chuàng)建兩個(gè)文件,一個(gè)用于 Push 動(dòng)畫,一個(gè)用于 Pop動(dòng)畫,然后 第3步 中在返回動(dòng)畫類之前,先判斷動(dòng)畫方式(Push 或 Pop), 使用 operation == UINavigationControllerOperation.Push 即可判斷,最后根據(jù)不同的方式返回不同的類。

    到這里就可以看到轉(zhuǎn)場動(dòng)畫的效果了,但是大家都知道,系統(tǒng)默認(rèn)的 Push 和 Pop 動(dòng)畫都支持手勢驅(qū)動(dòng),并且可以根據(jù)手勢移動(dòng)距離改變動(dòng)畫完成度。幸運(yùn)的是,Cocoa 已經(jīng)集成了相關(guān)方法,我們只用告訴它百分比就可以了。所以下一步就是 手勢驅(qū)動(dòng)
  4. 在第二個(gè) UIViewController 中給 View 添加一個(gè)滑動(dòng)(Pan)手勢。
    創(chuàng)建一個(gè) UIPercentDrivenInteractiveTransition 屬性。
    在手勢的監(jiān)聽方法中計(jì)算手勢移動(dòng)的百分比,并使用 UIPercentDrivenInteractiveTransition 屬性的 updateInteractiveTransition() 方法實(shí)時(shí)更新百分比。
    最后在手勢的 stateendedcancelled 時(shí),根據(jù)手勢完成度決定是還原動(dòng)畫還是結(jié)束動(dòng)畫,使用 UIPercentDrivenInteractiveTransition 屬性的 cancelInteractiveTransition()finishInteractiveTransition() 方法。

  5. 實(shí)現(xiàn) UINavigationControllerDelegate 中的另一個(gè)返回 UIViewControllerInteractiveTransitioning 的方法,并在其中返回 第4步 創(chuàng)建的 UIPercentDrivenInteractiveTransition 屬性。

至此,Push 和 Pop 方式的自定義就完成了,具體細(xì)節(jié)看下面的示例。

自定義 Push & Pop 示例

此示例來自 Kitten Yang 的blog 實(shí)現(xiàn)Keynote中的神奇移動(dòng)效果,我將其用 Swift 實(shí)現(xiàn)了一遍,源代碼地址: MagicMove,下面是運(yùn)行效果。

MagicMove.gif

初始化

  • 創(chuàng)建兩個(gè) ViewController,一個(gè)繼承自 UICollectionViewController,取名 ViewController。另一個(gè)繼承 UIViewController,取名 DetailViewController。在 Stroyboard 中創(chuàng)建并綁定。

  • Stroyboard 中拖一個(gè) UINavigationController,刪去默認(rèn)的 rootViewController,使 ViewController 作為其 rootViewController,再拖一條從 ViewControllerDetailViewController 的 segue。

  • ViewController 中自定義 UICollectionViewCell,添加 UIImageViewUILabel。

  • DetailViewController 中添加 UIImageViewUITextView

mm_inital.png

添加 UIViewControllerAnimatedTransitioning

  • 添加一個(gè) Cocoa Touch Class,繼承自 NSObject,取名 MagicMoveTransion,遵守 UIViewControllerAnimatedTransitioning 協(xié)議。

  • 實(shí)現(xiàn)協(xié)議的兩個(gè)方法,并在其中編寫 Push 的動(dòng)畫。 具體的動(dòng)畫實(shí)現(xiàn)過程都在代碼的注釋里 :

    func transitionDuration(transitionContext: UIViewControllerContextTransitioning) -> NSTimeInterval {
        return 0.5
    }
    
    func animateTransition(transitionContext: UIViewControllerContextTransitioning) {
        //1.獲取動(dòng)畫的源控制器和目標(biāo)控制器
        let fromVC = transitionContext.viewControllerForKey(UITransitionContextFromViewControllerKey) as! ViewController
        let toVC = transitionContext.viewControllerForKey(UITransitionContextToViewControllerKey) as! DetailViewController
        let container = transitionContext.containerView()
        
        //2.創(chuàng)建一個(gè) Cell 中 imageView 的截圖,并把 imageView 隱藏,造成使用戶以為移動(dòng)的就是 imageView 的假象
        let snapshotView = fromVC.selectedCell.imageView.snapshotViewAfterScreenUpdates(false)
        snapshotView.frame = container.convertRect(fromVC.selectedCell.imageView.frame, fromView: fromVC.selectedCell)
        fromVC.selectedCell.imageView.hidden = true
        
        //3.設(shè)置目標(biāo)控制器的位置,并把透明度設(shè)為0,在后面的動(dòng)畫中慢慢顯示出來變?yōu)?
        toVC.view.frame = transitionContext.finalFrameForViewController(toVC)
        toVC.view.alpha = 0
        
        //4.都添加到 container 中。注意順序不能錯(cuò)了
        container.addSubview(toVC.view)
        container.addSubview(snapshotView)
        
        //5.執(zhí)行動(dòng)畫
        UIView.animateWithDuration(transitionDuration(transitionContext), delay: 0, options: UIViewAnimationOptions.CurveEaseInOut, animations: { () -> Void in
                snapshotView.frame = toVC.avatarImageView.frame
                toVC.view.alpha = 1
            }) { (finish: Bool) -> Void in
                fromVC.selectedCell.imageView.hidden = false
                toVC.avatarImageView.image = toVC.image
                snapshotView.removeFromSuperview()
                
                //一定要記得動(dòng)畫完成后執(zhí)行此方法,讓系統(tǒng)管理 navigation
                transitionContext.completeTransition(true)
        }
    }
    

使用動(dòng)畫

  • ViewController 遵守 UINavigationControllerDelegate 協(xié)議。

  • ViewController 中設(shè)置 NavigationController 的代理為自己:

    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        
        self.navigationController?.delegate = self
    }
    
  • 實(shí)現(xiàn) UINavigationControllerDelegate 協(xié)議方法:

    func navigationController(navigationController: UINavigationController, animationControllerForOperation operation: UINavigationControllerOperation, fromViewController fromVC: UIViewController, toViewController toVC: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        if operation == UINavigationControllerOperation.Push {
            return MagicMoveTransion()
        } else {
            return nil
        }
    }
    
  • ViewControllercontrollerCell 的點(diǎn)擊方法中,發(fā)送 segue

    override func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        self.selectedCell = collectionView.cellForItemAtIndexPath(indexPath) as! MMCollectionViewCell
        
        self.performSegueWithIdentifier("detail", sender: nil)
    }
    
  • 在發(fā)送 segue 的時(shí)候,把點(diǎn)擊的 image 發(fā)送給 DetailViewController

    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        if segue.identifier == "detail" {
            let detailVC = segue.destinationViewController as! DetailViewController
            detailVC.image = self.selectedCell.imageView.image
        }
    }
    
    至此,在點(diǎn)擊 Cell 后,就會執(zhí)行剛剛自定義的動(dòng)畫了。接下來就要加入手勢驅(qū)動(dòng)。

手勢驅(qū)動(dòng)

  • DetailViewControllerViewDidAppear() 方法中,加入滑動(dòng)手勢。

        let edgePan = UIScreenEdgePanGestureRecognizer(target: self, action: Selector("edgePanGesture:"))
        edgePan.edges = UIRectEdge.Left
        self.view.addGestureRecognizer(edgePan)
    
  • 在手勢監(jiān)聽方法中,創(chuàng)建 UIPercentDrivenInteractiveTransition 屬性,并實(shí)現(xiàn)手勢百分比更新。

    func edgePanGesture(edgePan: UIScreenEdgePanGestureRecognizer) {
        let progress = edgePan.translationInView(self.view).x / self.view.bounds.width
        
        if edgePan.state == UIGestureRecognizerState.Began {
            self.percentDrivenTransition = UIPercentDrivenInteractiveTransition()
            self.navigationController?.popViewControllerAnimated(true)
        } else if edgePan.state == UIGestureRecognizerState.Changed {
            self.percentDrivenTransition?.updateInteractiveTransition(progress)
        } else if edgePan.state == UIGestureRecognizerState.Cancelled || edgePan.state == UIGestureRecognizerState.Ended {
            if progress > 0.5 {
                self.percentDrivenTransition?.finishInteractiveTransition()
            } else {
                self.percentDrivenTransition?.cancelInteractiveTransition()
            }
            self.percentDrivenTransition = nil
        }
    }
    
  • 實(shí)現(xiàn)返回 UIViewControllerInteractiveTransitioning 的方法并返回剛剛創(chuàng)建的 UIPercentDrivenInteractiveTransition屬性。

        func navigationController(navigationController: UINavigationController, interactionControllerForAnimationController animationController: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? {
        if animationController is MagicMovePopTransion {
            return self.percentDrivenTransition
        } else {
            return nil
        }
    }
    
OK,到現(xiàn)在,手勢驅(qū)動(dòng)就寫好了,但是還不能使用,因?yàn)檫€沒有實(shí)現(xiàn) Pop 方法!現(xiàn)在自己去實(shí)現(xiàn) Pop 動(dòng)畫吧!請參考源代碼:MagicMove

Modal

modal轉(zhuǎn)場方式即使用 presentViewController() 方法推出的方式,默認(rèn)情況下,第二個(gè)視圖從屏幕下方彈出。下面就來介紹下 modal 方式轉(zhuǎn)場動(dòng)畫的自定義。

  1. 創(chuàng)建一個(gè)文件繼承自 NSObject, 并遵守 UIViewControllerAnimatedTransitioning協(xié)議。

  2. 實(shí)現(xiàn)該協(xié)議的兩個(gè)基本方法:

    //指定轉(zhuǎn)場動(dòng)畫持續(xù)的時(shí)長
    func transitionDuration(transitionContext: UIViewControllerContextTransitioning) -> NSTimeInterval      
    //轉(zhuǎn)場動(dòng)畫的具體內(nèi)容       
    func animateTransition(transitionContext: UIViewControllerContextTransitioning)
    
    以上兩個(gè)步驟和 Push & Pop 的自定義一樣,接下來就是不同的。
  3. 如果使用 Modal 方式從一個(gè) VC 到另一個(gè) VC,那么需要第一個(gè) VC 遵循 UIViewControllerTransitioningDelegate 協(xié)議,并實(shí)現(xiàn)以下兩個(gè)協(xié)議方法:

    //present動(dòng)畫
    optional func animationControllerForPresentedController(presented: UIViewController, presentingController presenting: UIViewController, sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning?
    
    //dismiss動(dòng)畫
    optional func animationControllerForDismissedController(dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning?
    
  4. 在第一個(gè) VC 的 prepareForSegue() 方法中,指定第二個(gè) VC 的 transitioningDelegate 為 self。

    第3步 中兩個(gè)方法就可以知道,在創(chuàng)建轉(zhuǎn)場動(dòng)畫時(shí),最好也創(chuàng)建兩個(gè)動(dòng)畫類,一個(gè)用于 Present, 一個(gè)用于 Dismiss,如果只創(chuàng)建一個(gè)動(dòng)畫類,就需要在實(shí)現(xiàn)動(dòng)畫的時(shí)候判斷是 Present 還是 Dismiss。
    這時(shí),轉(zhuǎn)場動(dòng)畫就可以實(shí)現(xiàn)了,接下來就手勢驅(qū)動(dòng)了
  5. 在第一個(gè) VC 中創(chuàng)建一個(gè) UIPercentDrivenInteractiveTransition 屬性,并且在 prepareForSegue() 方法中為第二個(gè) VC.view 添加一個(gè)手勢,用以 dismiss. 在手勢的監(jiān)聽方法中處理方式和 Push & Pop 相同。

  6. 實(shí)現(xiàn) UIViewControllerTransitioningDelegate 協(xié)議的另外兩個(gè)方法,分別返回 PresentDismiss 動(dòng)畫的百分比。

    //百分比Push
    func interactionControllerForPresentation(animator: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? {
        return self.percentDrivenTransition
    }
    //百分比Pop
    func interactionControllerForDismissal(animator: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? {
        return self.percentDrivenTransition
    }
    
    至此,Modal 方式的自定義轉(zhuǎn)場動(dòng)畫就寫完了。自己在編碼的時(shí)候有一些小細(xì)節(jié)需要注意,下面將展示使用 Modal 方式的自定義動(dòng)畫的示例。

自定義 Modal 示例

此示例和上面一個(gè)示例一樣,來自 Kitten Yang 的blog 實(shí)現(xiàn)3D翻轉(zhuǎn)效果,我也將其用 Swift 實(shí)現(xiàn)了一遍,同樣我的源代碼地址:FlipTransion,運(yùn)行效果如下:

FlipTransion.gif

初始化

  • 創(chuàng)建兩個(gè) UIViewController, 分別命名為:FirstViewControllerSecondViewController。并在 Storyboard 中添加兩個(gè) UIViewController 并綁定。

  • 分別給兩個(gè)視圖添加兩個(gè) UIImageView,這樣做的目的是為了區(qū)分兩個(gè)控制器。當(dāng)然你也可以給兩個(gè)控制器設(shè)置不同的背景,總之你開心就好。但是,既然做,就做認(rèn)真點(diǎn)唄。注意:如果使用圖片并設(shè)置為 Aspect Fill 或者其他的 Fill,一定記得調(diào)用 imageViewclipsToBounds() 方法裁剪去多余的部分。

  • 分別給兩個(gè)控制器添加兩個(gè)按鈕,第一個(gè)按鈕拖線到第二個(gè)控制器,第二個(gè)控制器綁定一個(gè)方法用來dismiss。

ft_inital.png

添加 UIViewControllerAnimatedTransitioning

  • 添加一個(gè) Cocoa Touch Class,繼承自 NSObject,取名 BWFlipTransionPush(名字嘛,你開心就好。),遵守 UIViewControllerAnimatedTransitioning 協(xié)議。

  • 實(shí)現(xiàn)協(xié)議的兩個(gè)方法,并在其中編寫 Push 的動(dòng)畫。 具體的動(dòng)畫實(shí)現(xiàn)過程都在代碼的注釋里 :

    func animateTransition(transitionContext: UIViewControllerContextTransitioning) {
        let fromVC = transitionContext.viewControllerForKey(UITransitionContextFromViewControllerKey) as! FirstViewController
        let toVC = transitionContext.viewControllerForKey(UITransitionContextToViewControllerKey) as! SecondViewController
        let container = transitionContext.containerView()
        container.addSubview(toVC.view)
        container.bringSubviewToFront(fromVC.view)
        
        //改變m34
        var transfrom = CATransform3DIdentity
        transfrom.m34 = -0.002
        container.layer.sublayerTransform = transfrom
        
        //設(shè)置anrchPoint 和 position
        let initalFrame = transitionContext.initialFrameForViewController(fromVC)
        toVC.view.frame = initalFrame
        fromVC.view.frame = initalFrame
        fromVC.view.layer.anchorPoint = CGPointMake(0, 0.5)
        fromVC.view.layer.position = CGPointMake(0, initalFrame.height / 2.0)
        
        //添加陰影效果
        let shadowLayer = CAGradientLayer()
        shadowLayer.colors = [UIColor(white: 0, alpha: 1).CGColor, UIColor(white: 0, alpha: 0.5).CGColor, UIColor(white: 1, alpha: 0.5)]
        shadowLayer.startPoint = CGPointMake(0, 0.5)
        shadowLayer.endPoint = CGPointMake(1, 0.5)
        shadowLayer.frame = initalFrame
        let shadow = UIView(frame: initalFrame)
        shadow.backgroundColor = UIColor.clearColor()
        shadow.layer.addSublayer(shadowLayer)
        fromVC.view.addSubview(shadow)
        shadow.alpha = 0
        
        //動(dòng)畫
        UIView.animateWithDuration(transitionDuration(transitionContext), delay: 0, options: UIViewAnimationOptions.CurveEaseOut, animations: { () -> Void in
                fromVC.view.layer.transform = CATransform3DMakeRotation(CGFloat(-M_PI_2), 0, 1, 0)
                shadow.alpha = 1.0
            }) { (finished: Bool) -> Void in
                fromVC.view.layer.anchorPoint = CGPointMake(0.5, 0.5)
                fromVC.view.layer.position = CGPointMake(CGRectGetMidX(initalFrame), CGRectGetMidY(initalFrame))
                fromVC.view.layer.transform = CATransform3DIdentity
                shadow.removeFromSuperview()
                
                transitionContext.completeTransition(!transitionContext.transitionWasCancelled())
        }
    }
    

    動(dòng)畫的過程我就不多說了,仔細(xì)看就會明白。

使用動(dòng)畫

  • FirstViewController 遵守 UIViewControllerTransitioningDelegate 協(xié)議,并將 self.transitioningDelegate 設(shè)置為 self。

  • 實(shí)現(xiàn) UIViewControllerTransitioningDelegate 協(xié)議的兩個(gè)方法,用來指定動(dòng)畫類。

    //動(dòng)畫Push
    func animationControllerForPresentedController(presented: UIViewController, presentingController presenting: UIViewController, sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        return BWFlipTransionPush()
    }
    //動(dòng)畫Pop
    func animationControllerForDismissedController(dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        return BWFlipTransionPop()
    }
    
    OK,如果你完成了Pop動(dòng)畫,那么現(xiàn)在就可以實(shí)現(xiàn)自定義 Modal 轉(zhuǎn)場了?,F(xiàn)在只差手勢驅(qū)動(dòng)了。

手勢驅(qū)動(dòng)

  • 想要同時(shí)實(shí)現(xiàn) PushPop 手勢,就需要給兩個(gè) viewController.view 添加手勢。首先在 FirstViewController 中給自己添加一個(gè)屏幕右邊的手勢,在 prepareForSegue() 方法中給 SecondViewController.view 添加一個(gè)屏幕左邊的手勢,讓它們使用同一個(gè)手勢監(jiān)聽方法。

  • 實(shí)現(xiàn)監(jiān)聽方法,不多說,和之前一樣,但還是有仔細(xì)看,因?yàn)楸臼纠修D(zhuǎn)場動(dòng)畫比較特殊,而且有兩個(gè)手勢,所以這里計(jì)算百分比使用的是 KeyWindow。同時(shí)不要忘了:UIPercentDrivenInteractiveTransition屬性。

    func edgePanGesture(edgePan: UIScreenEdgePanGestureRecognizer) {
        let progress = abs(edgePan.translationInView(UIApplication.sharedApplication().keyWindow!).x) / UIApplication.sharedApplication().keyWindow!.bounds.width
        
        if edgePan.state == UIGestureRecognizerState.Began {
            self.percentDrivenTransition = UIPercentDrivenInteractiveTransition()
            if edgePan.edges == UIRectEdge.Right {
                self.performSegueWithIdentifier("present", sender: nil)
            } else if edgePan.edges == UIRectEdge.Left {
                self.dismissViewControllerAnimated(true, completion: nil)
            }
        } else if edgePan.state == UIGestureRecognizerState.Changed {
            self.percentDrivenTransition?.updateInteractiveTransition(progress)
        } else if edgePan.state == UIGestureRecognizerState.Cancelled || edgePan.state == UIGestureRecognizerState.Ended {
            if progress > 0.5 {
                self.percentDrivenTransition?.finishInteractiveTransition()
            } else {
                self.percentDrivenTransition?.cancelInteractiveTransition()
            }
            self.percentDrivenTransition = nil
        }
    }
    
  • 實(shí)現(xiàn) UIViewControllerTransitioningDelegate 協(xié)議的另外兩個(gè)方法,分別返回 PresentDismiss 動(dòng)畫的百分比。

    //百分比Push
    func interactionControllerForPresentation(animator: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? {
        return self.percentDrivenTransition
    }
    //百分比Pop
    func interactionControllerForDismissal(animator: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? {
        return self.percentDrivenTransition
    }
    
現(xiàn)在,基于 Modal 的自定義轉(zhuǎn)場動(dòng)畫示例就完成了。獲取完整源代碼:FlipTransion

Segue

這種方法比較特殊,是將 Stroyboard 中的拖線與自定義的 UIStoryboardSegue 類綁定自實(shí)現(xiàn)定義轉(zhuǎn)場過程動(dòng)畫。

首先我們來看看 UIStoryboardSegue 是什么樣的。

@availability(iOS, introduced=5.0)
class UIStoryboardSegue : NSObject {
    
    // Convenience constructor for returning a segue that performs a handler block in its -perform method.
    @availability(iOS, introduced=6.0)
    convenience init(identifier: String?, source: UIViewController, destination: UIViewController, performHandler: () -> Void)
    
    init!(identifier: String?, source: UIViewController, destination: UIViewController) // Designated initializer
    
    var identifier: String? { get }
    var sourceViewController: AnyObject { get }
    var destinationViewController: AnyObject { get }
    
    func perform()
}

以上是 UIStoryboardSegue 類的定義。從中可以看出,只有一個(gè)方法 perform(),所以很明顯,就是重寫這個(gè)方法來自定義轉(zhuǎn)場動(dòng)畫。

再注意它的其他屬性:sourceViewControllerdestinationViewController,通過這兩個(gè)屬性,我們就可以訪問一個(gè)轉(zhuǎn)場動(dòng)畫中的兩個(gè)主角了,于是自定義動(dòng)畫就可以隨心所欲了。

只有一點(diǎn)需要注意:在拖線的時(shí)候,注意在彈出的選項(xiàng)中選擇 custom。然后就可以和自定義的 UIStoryboardSegue 綁定了。

那么,問題來了,這里只有 perform,那 返回時(shí)的動(dòng)畫怎么辦呢?請往下看:

Dismiss

由于 perfrom 的方法叫做:segue,那么返回轉(zhuǎn)場的上一個(gè)控制器叫做: unwind segue

  • 解除轉(zhuǎn)場(unwind segue)通常和正常自定義轉(zhuǎn)場(segue)一起出現(xiàn)。
  • 要解除轉(zhuǎn)場起作用,我們必須重寫perform方法,并應(yīng)用自定義動(dòng)畫。另外,導(dǎo)航返回源視圖控制器的過渡效果不需要和對應(yīng)的正常轉(zhuǎn)場相同。

實(shí)現(xiàn)步驟 為:

  • 創(chuàng)建一個(gè) IBAction 方法,該方法在解除轉(zhuǎn)場被執(zhí)行的時(shí)候會選擇地執(zhí)行一些代碼。這個(gè)方法可以有你想要的任何名字,而且不強(qiáng)制包含其它東西。它需要定義,但可以留空,解除轉(zhuǎn)場的定義需要依賴這個(gè)方法。

  • 解除轉(zhuǎn)場的創(chuàng)建,設(shè)置的配置。這和之前的轉(zhuǎn)場創(chuàng)建不太一樣,等下我們將看看這個(gè)是怎么實(shí)現(xiàn)的。

  • 通過重寫 UIStoryboardSegue 子類里的 perform() 方法,來實(shí)現(xiàn)自定義動(dòng)畫。

  • UIViewController類 提供了特定方法的定義,所以系統(tǒng)知道解除轉(zhuǎn)場即將執(zhí)行。

當(dāng)然,這么說有一些讓人琢磨不透,不知道什么意思。那么,下面再通過一個(gè)示例來深入了解一下。

Segue 示例

這個(gè)示例是我自己寫的,源代碼地址:SegueTransion,開門見山,直接上圖。

GIF演示

SegueTransion.gif

初始化

  • 創(chuàng)建兩個(gè) UIViewController, 分別命名為:FirstViewControllerSecondViewController。并在 Storyboard 中添加兩個(gè) UIViewController 并綁定。

  • 分別給兩個(gè)控制器添加背景圖片或使用不同的背景色,用以區(qū)分。在 FirstViewController 中添加一個(gè)觸發(fā)按鈕,并拖線到 SecondViewController 中,在彈出的選項(xiàng)中選擇 custion。

st_inital.png

Present

  • 添加一個(gè) Cocoa Touch Class,繼承自 UIStoryboardSegue,取名 FirstSegue(名字請隨意)。并將其綁定到上一步中拖拽的 segue 上。

  • 重寫 FirstSegue 中的 perform() 方法,在其中編寫動(dòng)畫邏輯。

    override func perform() {
        var firstVCView = self.sourceViewController.view as UIView!
        var secondVCView = self.destinationViewController.view as UIView!
        
        let screenWidth = UIScreen.mainScreen().bounds.size.width
        let screenHeight = UIScreen.mainScreen().bounds.size.height
        
        secondVCView.frame = CGRectMake(0.0, screenHeight, screenWidth, screenHeight)
        let window = UIApplication.sharedApplication().keyWindow
        window?.insertSubview(secondVCView, aboveSubview: firstVCView)
        
        UIView.animateWithDuration(0.5, delay: 0, usingSpringWithDamping: 0.5, initialSpringVelocity: 0, options: UIViewAnimationOptions.CurveLinear, animations: { () -> Void in
                secondVCView.frame = CGRectOffset(secondVCView.frame, 0.0, -screenHeight)
            }) { (finished: Bool) -> Void in
                self.sourceViewController.presentViewController(self.destinationViewController as! UIViewController,
                    animated: false,
                    completion: nil)
        }
    }
    

    還是一樣,動(dòng)畫的過程自己看,都是很簡單的。

Present手勢

這里需要注意,使用這種方式自定義的轉(zhuǎn)場動(dòng)畫不能動(dòng)態(tài)手勢驅(qū)動(dòng),也就是說不能根據(jù)手勢百分比動(dòng)態(tài)改變動(dòng)畫完成度。
所以,這里只是簡單的添加一個(gè)滑動(dòng)手勢(swip)。

  • FisrtViewController 中添加手勢:

    var swipeGestureRecognizer: UISwipeGestureRecognizer = UISwipeGestureRecognizer(target: self, action: "showSecondViewController")
    swipeGestureRecognizer.direction = UISwipeGestureRecognizerDirection.Up
    self.view.addGestureRecognizer(swipeGestureRecognizer)
    
  • 實(shí)現(xiàn)手勢監(jiān)聽方法:

    func showSecondViewController() {
        self.performSegueWithIdentifier("idFirstSegue", sender: self)
    }
    
現(xiàn)在已經(jīng)可以 present 了,接下來實(shí)現(xiàn) dismiss。

Dismiss

  • FirstViewController 中添加一個(gè) IBAction 方法,方法名可以隨便,有沒有返回值都隨便。

  • Storyboard 中選擇 SecondViewController 按住 control鍵 拖線到 SecondViewControllerExit 圖標(biāo)。并在彈出選項(xiàng)中選擇上一步添加 IBAction 的方法。

st_unwind.png
  • Storyboard 左側(cè)的文檔視圖中找到上一步拖的 segue,并設(shè)置 identifier
st_unwindSegue.png
  • 再添加一個(gè) Cocoa Touch Class,繼承自 UIStoryboardSegue,取名 FirstSegueUnWind(名字請隨意)。并重寫其 perform() 方法,用來實(shí)現(xiàn) dismiss 動(dòng)畫。

  • FirstViewController 中重寫下面方法。并根據(jù) identifier 判斷是不是需要 dismiss,如果是就返回剛剛創(chuàng)建的 FirstUnWindSegue

    override func segueForUnwindingToViewController(toViewController: UIViewController, fromViewController: UIViewController, identifier: String?) -> UIStoryboardSegue {
        
        if identifier == "firstSegueUnwind" {
            return FirstUnwindSegue(identifier: identifier, source: fromViewController, destination: toViewController, performHandler: { () -> Void in
            })
        }
        
        return super.segueForUnwindingToViewController(toViewController, fromViewController: fromViewController, identifier: identifier)
    }
    
  • 最后一步,在 SecondViewController 的按鈕的監(jiān)聽方法中實(shí)現(xiàn) dismiss, 注意不是調(diào)用 self.dismiss...!

    @IBAction func shouldDismiss(sender: AnyObject) {
        self.performSegueWithIdentifier("firstSegueUnwind", sender: self)
    }
    
    SecondViewController 添加手勢,將手勢監(jiān)聽方法也設(shè)置為以上這個(gè)方法, 參考代碼:SegueTransion。

總結(jié)

一張圖總結(jié)一下3種方法的異同點(diǎn)。

總結(jié).png

到這里,終于吧3中方法的自定義都寫完了,寫這篇 blog 花了我一天的時(shí)間!希望我自己和看過的同學(xué)都能記??!同時(shí),有錯(cuò)誤的地方歡迎提出。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容