LoginSignup
12
10

More than 5 years have passed since last update.

タブ切り替え時にアニメーションを行う

Last updated at Posted at 2015-07-25

UITabbarController のタブをアニメーションで切り替わるようにする。

おおまかに次の手順

  1. UIViewControllerAnimatedTransitioning プロトコルに準拠したアニメーションクラスを作成する。
  2. TabBarControllerDelegate のanimationControllerForTransitionFromViewController メソッド内で上記のアニメーションクラスを返してやればOK

1.animator クラスの作成

TabAnimation
class TabAnimation: NSObject,UIViewControllerAnimatedTransitioning {

    func transitionDuration(transitionContext: UIViewControllerContextTransitioning) -> NSTimeInterval {
        return 1.0
    }

    func animateTransition(transitionContext: UIViewControllerContextTransitioning) {
        let from:UIViewController = transitionContext.viewControllerForKey(UITransitionContextFromViewControllerKey)!
        let to:UIViewController = transitionContext.viewControllerForKey(UITransitionContextToViewControllerKey)!
        var container:UIView = transitionContext.containerView()
        container.insertSubview(to.view, aboveSubview: from.view)
        to.view.alpha = 0.0;

        UIView.animateWithDuration(self.transitionDuration(transitionContext),
            animations: {() -> Void in

                println("begin")
                from.view.alpha = 0.0;
                to.view.alpha = 1.0;

            },
            completion: {(value: Bool) in
                transitionContext.completeTransition(true)
        })
    }

}
  1. タブコントローラの実装
TabViewController
class TabViewController: UITabBarController,UITabBarControllerDelegate {
    override func viewDidLoad() {
        super.viewDidLoad()
 self.delegate = self
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

    func tabBarController(tabBarController: UITabBarController, didSelectViewController viewController: UIViewController) {
        println(viewController)
    }

    func tabBarController(tabBarController: UITabBarController,
        animationControllerForTransitionFromViewController fromVC: UIViewController,
        toViewController toVC: UIViewController) -> UIViewControllerAnimatedTransitioning?{
            return TabAnimation()
    }
}

作ったやつのサンプルプロジェクトはこちら
https://github.com/colorbox/Example/tree/master/AnimationTab

12
10
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
12
10