如何使选项卡栏过渡动画在没有初始视图控制器的情况下也可以工作

时间:2019-06-06 04:56:41

标签: swift

基本上,我为标签栏控制器具有以下自定义过渡动画:

MyFadeTransition.swift

import UIKit

class MyFadeTransition: NSObject, UIViewControllerAnimatedTransitioning {
    func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
        if let fromVC = transitionContext.viewController(forKey: .from), let toVC = transitionContext.viewController(forKey: .to) {
            toVC.view.frame = fromVC.view.frame
            toVC.view.alpha = 0
            fromVC.view.alpha = 1
            transitionContext.containerView.addSubview(fromVC.view)
            transitionContext.containerView.addSubview(toVC.view)

            UIView.animate(withDuration: transitionDuration(using: transitionContext), animations: {
                toVC.view.alpha = 1
            }) { (finished) in
                transitionContext.completeTransition(finished)
            }
        }
    }

    func animationEnded(_ transitionCompleted: Bool) {
        // no-op
    }

    func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
        return 0.12
    }
}

问题在于该代码还需要在启动过程中将Tab Bar Controller用作初始视图控制器,而下面的代码AppDelegate

let tab = window!.rootViewController as! UITabBarController
tab.delegate = self

还必须将以下内容添加到 AppDelegate.swift

extension AppDelegate: UITabBarControllerDelegate {
    func tabBarController(_ tabBarController: UITabBarController, animationControllerForTransitionFrom fromVC: UIViewController, to toVC: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        let fade = MyFadeTransition()

        return fade
    }
}

我正在使用其他ViewController作为初始ViewController,如何在不将其作为初始控制器的情况下使代码继续工作?

1 个答案:

答案 0 :(得分:0)

您需要继承UITabBarController并使用

class CustomTab:UITabBarController,UITabBarControllerDelegate { 
   override func viewDidLoad() {
      super.viewDidLoad()
      self.delegate = self
   }
   func tabBarController(_ tabBarController: UITabBarController, animationControllerForTransitionFrom fromVC: UIViewController, to toVC: UIViewController) -> UIViewControllerAnimatedTransitioning? { 
      return MyFadeTransition()
   }
}

然后将CustomTab作为类名称分配给IB中的tabBar