关于自定义转场动画,我都告诉你

做者:@翁呀伟呀  git

概述 github

这篇文章,我将讲述几种转场动画的自定义方式,而且每种方式附上一个示例,毕竟代码才是咱们的语言,这样比较容易上手。其中主要有如下三种自定义方法,供你们参考: ide

  • Push & Pop 动画

  • Modal 编码

  • Segue spa

前两种你们都很熟悉,第三种是 Stroyboard 中的拖线,属于 UIStoryboardSegue 类,经过继承这个类来自定义转场过程动画。 3d

Push & Pop 代理

首先说一下 Push & Pop 这种转场的自定义,操做步骤以下: orm

1. 建立一个文件继承自 NSObject, 并遵照 UIViewControllerAnimatedTransitioning协议。 blog

2. 实现该协议的两个基本方法:

1
2
3
4
//指定转场动画持续的时长
func transitionDuration(transitionContext: UIViewControllerContextTransitioning) -> NSTimeInterval      
//转场动画的具体内容       
func animateTransition(transitionContext: UIViewControllerContextTransitioning)

3. 遵照 UINavigationControllerDelegate 协议,并实现此方法:

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

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

注意:因为须要 Push 和 Pop,因此须要两套动画方案。解决方法为:

在 第1步 中,建立两个文件,一个用于 Push 动画,一个用于 Pop动画,而后 第3步 中在返回动画类以前,先判断动画方式(Push 或 Pop), 使用 operation == UINavigationControllerOperation.Push 便可判断,最后根据不一样的方式返回不一样的类。

到这里就能够看到转场动画的效果了,可是你们都知道,系统默认的 Push 和 Pop 动画都支持手势驱动,而且能够根据手势移动距离改变更画完成度。幸运的是,Cocoa 已经集成了相关方法,咱们只用告诉它百分比就能够了。因此下一步就是 手势驱动。

4. 在第二个 UIViewController 中给 View 添加一个滑动(Pan)手势。

建立一个 UIPercentDrivenInteractiveTransition 属性。

在手势的监听方法中计算手势移动的百分比,并使用 UIPercentDrivenInteractiveTransition 属性的 updateInteractiveTransition() 方法实时更新百分比。

最后在手势的 state 为 ended 或 cancelled 时,根据手势完成度决定是还原动画仍是结束动画,使用 UIPercentDrivenInteractiveTransition 属性的 cancelInteractiveTransition() 或 finishInteractiveTransition() 方法。

5. 实现 UINavigationControllerDelegate 中的另外一个返回 UIViewControllerInteractiveTransitioning 的方法,并在其中返回 第4步 建立的 UIPercentDrivenInteractiveTransition 属性。

至此,Push 和 Pop 方式的自定义就完成了,具体细节看下面的示例。

自定义 Push & Pop 示例

此示例来自 Kitten Yang 的blog 实现Keynote中的神奇移动效果,我将其用 Swift 实现了一遍,源代码地址: MagicMove,下面是运行效果。

1 (2).gif

初始化

  • 建立两个 ViewController,一个继承自 UICollectionViewController,取名 ViewController。另外一个继承 UIViewController,取名 DetailViewController。在 Stroyboard 中建立并绑定。

  • 在 Stroyboard 中拖一个 UINavigationController,删去默认的 rootViewController,使 ViewController 做为其 rootViewController,再拖一条从 ViewController 到 DetailViewController 的 segue。

  • 在 ViewController 中自定义 UICollectionViewCell,添加 UIImageView 和 UILabel。

  • 在 DetailViewController 中添加 UIImageView 和 UITextView

blob.png

添加 UIViewControllerAnimatedTransitioning

  • 添加一个 Cocoa Touch Class,继承自 NSObject,取名 MagicMoveTransion,遵照 UIViewControllerAnimatedTransitioning 协议。

  • 实现协议的两个方法,并在其中编写 Push 的动画。 具体的动画实现过程都在代码的注释里 :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
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 的代理为本身:

1
2
3
4
override func viewDidAppear(animated: Bool) {
    super.viewDidAppear(animated)
    self.navigationController?.delegate = self
}
  • 实现 UINavigationControllerDelegate 协议方法:

1
2
3
4
5
6
7
func navigationController(navigationController: UINavigationController, animationControllerForOperation operation: UINavigationControllerOperation, fromViewController fromVC: UIViewController, toViewController toVC: UIViewController) -> UIViewControllerAnimatedTransitioning? {
    if operation == UINavigationControllerOperation.Push {
        return MagicMoveTransion()
    } else {
        return nil
    }
}
  • 在 ViewController 的 controllerCell 的点击方法中,发送 segue

1
2
3
4
override func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
    self.selectedCell = collectionView.cellForItemAtIndexPath(indexPath) as! MMCollectionViewCell
    self.performSegueWithIdentifier("detail", sender: nil)
}
  • 在发送 segue 的时候,把点击的 image 发送给 DetailViewController

1
2
3
4
5
6
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    if segue.identifier == "detail" {
        let detailVC = segue.destinationViewController as! DetailViewController
        detailVC.image = self.selectedCell.imageView.image
    }
}

至此,在点击 Cell 后,就会执行刚刚自定义的动画了。接下来就要加入手势驱动。

手势驱动

  • 在 DetailViewController 的 ViewDidAppear() 方法中,加入滑动手势。

1
2
3
let edgePan = UIScreenEdgePanGestureRecognizer(target: self, action: Selector("edgePanGesture:"))
    edgePan.edges = UIRectEdge.Left
    self.view.addGestureRecognizer(edgePan)
  • 在手势监听方法中,建立 UIPercentDrivenInteractiveTransition 属性,并实现手势百分比更新。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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属性。

1
2
3
4
5
6
7
    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. 实现该协议的两个基本方法:

1
2
3
4
//指定转场动画持续的时长
func transitionDuration(transitionContext: UIViewControllerContextTransitioning) -> NSTimeInterval      
//转场动画的具体内容       
func animateTransition(transitionContext: UIViewControllerContextTransitioning)

以上两个步骤和 Push & Pop 的自定义同样,接下来就是不一样的。

3. 若是使用 Modal 方式从一个 VC 到另外一个 VC,那么须要第一个 VC 遵循 UIViewControllerTransitioningDelegate 协议,并实现如下两个协议方法:

1
2
3
4
 //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 协议的另外两个方法,分别返回 Present 和 Dismiss 动画的百分比。

1
2
3
4
5
6
7
8
 //百分比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,运行效果以下:

2.gif

初始化

  • 建立两个 UIViewController, 分别命名为:FirstViewController 和 SecondViewController。并在 Storyboard 中添加两个 UIViewController 并绑定。

  • 分别给两个视图添加两个 UIImageView,这样作的目的是为了区分两个控制器。固然你也能够给两个控制器设置不一样的背景,总之你开心就好。可是,既然作,就作认真点呗。注意:若是使用图片并设置为 Aspect Fill 或者其余的 Fill,必定记得调用 imageView 的 clipsToBounds() 方法裁剪去多余的部分。

  • 分别给两个控制器添加两个按钮,第一个按钮拖线到第二个控制器,第二个控制器绑定一个方法用来dismiss。

blob.png

添加 UIViewControllerAnimatedTransitioning

  • 添加一个 Cocoa Touch Class,继承自 NSObject,取名 BWFlipTransionPush(名字嘛,你开心就好。),遵照 UIViewControllerAnimatedTransitioning 协议。

  • 实现协议的两个方法,并在其中编写 Push 的动画。 具体的动画实现过程都在代码的注释里 :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
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 协议的两个方法,用来指定动画类。

1
2
3
4
5
6
7
8
//动画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 转场了。如今只差手势驱动了。

手势驱动

  • 想要同时实现 Push 和 Pop 手势,就须要给两个 viewController.view 添加手势。首先在 FirstViewController 中给本身添加一个屏幕右边的手势,在 prepareForSegue() 方法中给 SecondViewController.view 添加一个屏幕左边的手势,让它们使用同一个手势监听方法。

  • 实现监听方法,很少说,和以前同样,但仍是有仔细看,由于本示例中转场动画比较特殊,并且有两个手势,因此这里计算百分比使用的是 KeyWindow。同时不要忘了:UIPercentDrivenInteractiveTransition属性。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
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 协议的另外两个方法,分别返回 Present 和 Dismiss 动画的百分比。

1
2
3
4
5
6
7
8
//百分比Push
func interactionControllerForPresentation(animator: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? {
    return self.percentDrivenTransition
}
//百分比Pop
func interactionControllerForDismissal(animator: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? {
    return self.percentDrivenTransition
}

如今,基于 Modal 的自定义转场动画示例就完成了。获取完整源代码:FlipTransion

Segue

这种方法比较特殊,是将 Stroyboard 中的拖线与自定义的 UIStoryboardSegue 类绑定自实现定义转场过程动画。

首先咱们来看看 UIStoryboardSegue 是什么样的。

1
2
3
4
5
6
7
8
9
10
11
@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(),因此很明显,就是重写这个方法来自定义转场动画。

再注意它的其余属性:sourceViewController 和 destinationViewController,经过这两个属性,咱们就能够访问一个转场动画中的两个主角了,因而自定义动画就能够为所欲为了。

只有一点须要注意:在拖线的时候,注意在弹出的选项中选择 custom。而后就能够和自定义的 UIStoryboardSegue 绑定了。

那么,问题来了,这里只有 perform,那 返回时的动画怎么办呢?请往下看:

Dismiss

因为 perfrom 的方法叫作:segue,那么返回转场的上一个控制器叫作: unwind segue

  • 解除转场(unwind segue)一般和正常自定义转场(segue)一块儿出现。

  • 要解除转场起做用,咱们必须重写perform方法,并应用自定义动画。另外,导航返回源视图控制器的过渡效果不须要和对应的正常转场相同。

其 实现步骤 为:

  • 建立一个 IBAction 方法,该方法在解除转场被执行的时候会选择地执行一些代码。这个方法能够有你想要的任何名字,并且不强制包含其它东西。它须要定义,但能够留空,解除转场的定义须要依赖这个方法。

  • 解除转场的建立,设置的配置。这和以前的转场建立不太同样,等下咱们将看看这个是怎么实现的。

  • 经过重写 UIStoryboardSegue 子类里的 perform() 方法,来实现自定义动画。

  • UIViewController类 提供了特定方法的定义,因此系统知道解除转场即将执行。

固然,这么说有一些让人琢磨不透,不知道什么意思。那么,下面再经过一个示例来深刻了解一下。

Segue 示例

这个示例是我本身写的,源代码地址:SegueTransion,开门见山,直接上图。

GIF演示

3.gif

初始化

  • 建立两个 UIViewController, 分别命名为:FirstViewController 和 SecondViewController。并在 Storyboard 中添加两个 UIViewController 并绑定。

  • 分别给两个控制器添加背景图片或使用不一样的背景色,用以区分。在 FirstViewController 中添加一个触发按钮,并拖线到 SecondViewController 中,在弹出的选项中选择 custion。

blob.png

Present

  • 添加一个 Cocoa Touch Class,继承自 UIStoryboardSegue,取名 FirstSegue(名字请随意)。并将其绑定到上一步中拖拽的 segue 上。

  • 重写 FirstSegue 中的 perform() 方法,在其中编写动画逻辑。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
  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 中添加手势:

1
2
3
  var swipeGestureRecognizer: UISwipeGestureRecognizer = UISwipeGestureRecognizer(target: self, action: "showSecondViewController")
  swipeGestureRecognizer.direction = UISwipeGestureRecognizerDirection.Up
  self.view.addGestureRecognizer(swipeGestureRecognizer)
  • 实现手势监听方法:

1
2
3
func showSecondViewController() {
    self.performSegueWithIdentifier("idFirstSegue", sender: self)
}

如今已经能够 present 了,接下来实现 dismiss。

Dismiss

  • 在 FirstViewController 中添加一个 IBAction 方法,方法名能够随便,有没有返回值都随便。

  • 在 Storyboard 中选择 SecondViewController 按住 control键 拖线到 SecondViewController 的 Exit 图标。并在弹出选项中选择上一步添加 IBAction 的方法。

blob.png

  • 在 Storyboard 左侧的文档视图中找到上一步拖的 segue,并设置 identifier

blob.png

  • 再添加一个 Cocoa Touch Class,继承自 UIStoryboardSegue,取名 FirstSegueUnWind(名字请随意)。并重写其 perform() 方法,用来实现 dismiss 动画。

  • 在 FirstViewController 中重写下面方法。并根据 identifier 判断是否是须要 dismiss,若是是就返回刚刚建立的 FirstUnWindSegue。

1
2
3
4
5
6
7
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...!

1
2
3
  @IBAction func shouldDismiss(sender: AnyObject) {
      self.performSegueWithIdentifier("firstSegueUnwind", sender: self)
  }

给 SecondViewController 添加手势,将手势监听方法也设置为以上这个方法, 参考代码:SegueTransion

总结

一张图总结一下3种方法的异同点。

blob.png

到这里,终于吧3中方法的自定义都写完了,写这篇 blog 花了我一天的时间!但愿我本身和看过的同窗都能记住!同时,有错误的地方欢迎提出。

相关文章
相关标签/搜索