關于自定義轉場動畫,我都告訴你。

概述

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

  • Push & Pop
  • Modal
  • Segue

前兩種大家都很熟悉,第三種是 Stroyboard 中的拖線,屬于 UIStoryboardSegue 類,通過繼承這個類來自定義轉場過程動畫。

Push & Pop

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

  1. 創建一個文件繼承自 NSObject, 并遵守 UIViewControllerAnimatedTransitioning協議。

  2. 實現該協議的兩個基本方法:

    //指定轉場動畫持續的時長
    func transitionDuration(transitionContext: UIViewControllerContextTransitioning) -> NSTimeInterval      
    //轉場動畫的具體內容       
    func animateTransition(transitionContext: UIViewControllerContextTransitioning)
    
  3. 遵守 UINavigationControllerDelegate 協議,并實現此方法:

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

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

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

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

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

  5. 實現 UINavigationControllerDelegate 中的另一個返回 UIViewControllerInteractiveTransitioning 的方法,并在其中返回 第4步 創建的 UIPercentDrivenInteractiveTransition 屬性。

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

自定義 Push & Pop 示例

此示例來自 Kitten Yang 的blog 實現Keynote中的神奇移動效果,我將其用 Swift 實現了一遍,源代碼地址: MagicMove,下面是運行效果。

MagicMove.gif

初始化

  • 創建兩個 ViewController,一個繼承自 UICollectionViewController,取名 ViewController。另一個繼承 UIViewController,取名 DetailViewController。在 Stroyboard 中創建并綁定。

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

  • ViewController 中自定義 UICollectionViewCell,添加 UIImageViewUILabel

  • DetailViewController 中添加 UIImageViewUITextView

mm_inital.png

添加 UIViewControllerAnimatedTransitioning

  • 添加一個 Cocoa Touch Class,繼承自 NSObject,取名 MagicMoveTransion,遵守 UIViewControllerAnimatedTransitioning 協議。

  • 實現協議的兩個方法,并在其中編寫 Push 的動畫。 具體的動畫實現過程都在代碼的注釋里 :

    func transitionDuration(transitionContext: UIViewControllerContextTransitioning) -> NSTimeInterval {
        return 0.5
    }
    
    func animateTransition(transitionContext: UIViewControllerContextTransitioning) {
        //1.獲取動畫的源控制器和目標控制器
        let fromVC = transitionContext.viewControllerForKey(UITransitionContextFromViewControllerKey) as! ViewController
        let toVC = transitionContext.viewControllerForKey(UITransitionContextToViewControllerKey) as! DetailViewController
        let container = transitionContext.containerView()
        
        //2.創建一個 Cell 中 imageView 的截圖,并把 imageView 隱藏,造成使用戶以為移動的就是 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.設置目標控制器的位置,并把透明度設為0,在后面的動畫中慢慢顯示出來變為1
        toVC.view.frame = transitionContext.finalFrameForViewController(toVC)
        toVC.view.alpha = 0
        
        //4.都添加到 container 中。注意順序不能錯了
        container.addSubview(toVC.view)
        container.addSubview(snapshotView)
        
        //5.執行動畫
        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()
                
                //一定要記得動畫完成后執行此方法,讓系統管理 navigation
                transitionContext.completeTransition(true)
        }
    }
    

使用動畫

  • ViewController 遵守 UINavigationControllerDelegate 協議。

  • ViewController 中設置 NavigationController 的代理為自己:

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

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

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

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

手勢驅動

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

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

    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
        }
    }
    
  • 實現返回 UIViewControllerInteractiveTransitioning 的方法并返回剛剛創建的 UIPercentDrivenInteractiveTransition屬性。

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

Modal

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

  1. 創建一個文件繼承自 NSObject, 并遵守 UIViewControllerAnimatedTransitioning協議。

  2. 實現該協議的兩個基本方法:

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

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

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

  6. 實現 UIViewControllerTransitioningDelegate 協議的另外兩個方法,分別返回 PresentDismiss 動畫的百分比。

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

自定義 Modal 示例

此示例和上面一個示例一樣,來自 Kitten Yang 的blog 實現3D翻轉效果,我也將其用 Swift 實現了一遍,同樣我的源代碼地址:FlipTransion,運行效果如下:

FlipTransion.gif

初始化

  • 創建兩個 UIViewController, 分別命名為:FirstViewControllerSecondViewController。并在 Storyboard 中添加兩個 UIViewController 并綁定。

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

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

ft_inital.png

添加 UIViewControllerAnimatedTransitioning

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

  • 實現協議的兩個方法,并在其中編寫 Push 的動畫。 具體的動畫實現過程都在代碼的注釋里 :

    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
        
        //設置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
        
        //動畫
        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())
        }
    }
    

    動畫的過程我就不多說了,仔細看就會明白。

使用動畫

  • FirstViewController 遵守 UIViewControllerTransitioningDelegate 協議,并將 self.transitioningDelegate 設置為 self。

  • 實現 UIViewControllerTransitioningDelegate 協議的兩個方法,用來指定動畫類。

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

手勢驅動

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

  • 實現監聽方法,不多說,和之前一樣,但還是有仔細看,因為本示例中轉場動畫比較特殊,而且有兩個手勢,所以這里計算百分比使用的是 KeyWindow。同時不要忘了: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
        }
    }
    
  • 實現 UIViewControllerTransitioningDelegate 協議的另外兩個方法,分別返回 PresentDismiss 動畫的百分比。

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

Segue

這種方法比較特殊,是將 Stroyboard 中的拖線與自定義的 UIStoryboardSegue 類綁定自實現定義轉場過程動畫。

首先我們來看看 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 類的定義。從中可以看出,只有一個方法 perform(),所以很明顯,就是重寫這個方法來自定義轉場動畫。

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

只有一點需要注意:在拖線的時候,注意在彈出的選項中選擇 custom。然后就可以和自定義的 UIStoryboardSegue 綁定了。

那么,問題來了,這里只有 perform,那 返回時的動畫怎么辦呢?請往下看:

Dismiss

由于 perfrom 的方法叫做:segue,那么返回轉場的上一個控制器叫做: unwind segue

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

實現步驟 為:

  • 創建一個 IBAction 方法,該方法在解除轉場被執行的時候會選擇地執行一些代碼。這個方法可以有你想要的任何名字,而且不強制包含其它東西。它需要定義,但可以留空,解除轉場的定義需要依賴這個方法。

  • 解除轉場的創建,設置的配置。這和之前的轉場創建不太一樣,等下我們將看看這個是怎么實現的。

  • 通過重寫 UIStoryboardSegue 子類里的 perform() 方法,來實現自定義動畫。

  • UIViewController類 提供了特定方法的定義,所以系統知道解除轉場即將執行。

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

Segue 示例

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

GIF演示

SegueTransion.gif

初始化

  • 創建兩個 UIViewController, 分別命名為:FirstViewControllerSecondViewController。并在 Storyboard 中添加兩個 UIViewController 并綁定。

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

st_inital.png

Present

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

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

    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)
        }
    }
    

    還是一樣,動畫的過程自己看,都是很簡單的。

Present手勢

這里需要注意,使用這種方式自定義的轉場動畫不能動態手勢驅動,也就是說不能根據手勢百分比動態改變動畫完成度。
所以,這里只是簡單的添加一個滑動手勢(swip)。

  • FisrtViewController 中添加手勢:

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

    func showSecondViewController() {
        self.performSegueWithIdentifier("idFirstSegue", sender: self)
    }
    
現在已經可以 present 了,接下來實現 dismiss

Dismiss

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

  • Storyboard 中選擇 SecondViewController 按住 control鍵 拖線到 SecondViewControllerExit 圖標。并在彈出選項中選擇上一步添加 IBAction 的方法。

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

  • FirstViewController 中重寫下面方法。并根據 identifier 判斷是不是需要 dismiss,如果是就返回剛剛創建的 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 的按鈕的監聽方法中實現 dismiss, 注意不是調用 self.dismiss...!

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

總結

一張圖總結一下3種方法的異同點。

總結.png

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

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容