IOS实战之自定义转场动画详解

2020-01-14 20:18:51丽君

  • 设置presentedViewController的视图大小
  • 添加自定义视图来改变presentedView的外观
  • 为任何自定义的视图提供转场动画效果
  • 根据size class进行响应式布局

    您可以认为,. FullScreen以及其他present风格都是swift为我们实现提供好的,它们是.Custom的特例。而.Custom允许我们更加自由的定义转场动画效果。

    UIPresentationController提供了四个函数来定义present和dismiss动画开始前后的操作:

    • presentationTransitionWillBegin: present将要执行时
    • presentationTransitionDidEnd:present执行结束后
    • dismissalTransitionWillBegin:dismiss将要执行时
    • dismissalTransitionDidEnd:dismiss执行结束后

      下面的代码简要描述了gif中第三个动画效果的实现原理,您可以在demo的Custom Presentation文件夹下查看完成代码:

       

      
      // 这个相当于fromViewController
      class CustomPresentationFirstViewController: UIViewController {
        // 这个相当于toViewController
        lazy var customPresentationSecondViewController: CustomPresentationSecondViewController = CustomPresentationSecondViewController()
        // 创建PresentationController
        lazy var customPresentationController: CustomPresentationController = CustomPresentationController(presentedViewController: self.customPresentationSecondViewController, presentingViewController: self)
      
        override func viewDidLoad() {
          super.viewDidLoad()
          setupView() // 主要是一些UI控件的布局,可以无视其实现细节
      
          // 设置转场动画代理
          customPresentationSecondViewController.transitioningDelegate = customPresentationController
        }
      
        override func didReceiveMemoryWarning() {
          super.didReceiveMemoryWarning()
          // Dispose of any resources that can be recreated.
        }
      
        func animationButtonDidClicked() {
          self.presentViewController(customPresentationSecondViewController, animated: true, completion: nil)
        }
      }
      
      

      重点在于如何实现CustomPresentationController这个类: