はじめに
こんにちは、nukkyです。
今回は、UITabBarControllerの切り替え時にアニメーションを実装できるライブラリ「TransitionableTab」を紹介したいと思います。
準備
今回もおなじみCarthageを使用します。
Cartfileにこちらを記述してください。
1 | github"Interactive-Studio/TransitionableTab"~>0.1.2 |
そうしたら、以下のコマンドでビルドしてください。
1 | carthage update--platform iOS |
実装
まずは以下のインポートを行ってください。
1 2 | importUIKit importTransitionableTab |
enumでアニメーションのタイプを定義しておきます。
「TransitionableTab」では基本的なアニメーションとして「move」「scale」「fade」が用意されています各アニメーションの動きについては後ほど
1 2 3 4 5 6 7 8 | enumType: String{ casemove casefade casescale casecustom staticvarall:[Type]=[.move,.scale,.fade,.custom] } |
UITabBarControllerでクラスを作成します。
アニメーション選択変数を用意しておき、viewDidLoadでdelegateにselfを設定します。
1 2 3 4 5 6 7 8 9 10 | classTabBarController: UITabBarController{ // アニメーション設定用 vartype:Type=.custom overridefuncviewDidLoad(){ super.viewDidLoad() self.delegate=self } } |
extensionで「TransitionableTab」のプロトコルを継承します。
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 | extensionTabBarController: TransitionableTab{ funcfromTransitionAnimation(layer:CALayer,direction:Direction)->CAAnimation{ switchtype{ case.move:returnDefineAnimation.move(.from,direction:direction) case.scale:returnDefineAnimation.scale(.from) case.fade:returnDefineAnimation.fade(.from) case.custom: letanimation=CABasicAnimation(keyPath:"transform.translation.y") animation.fromValue=0 animation.toValue=-layer.frame.height returnanimation } } functoTransitionAnimation(layer:CALayer,direction:Direction)->CAAnimation{ switchtype{ case.move:returnDefineAnimation.move(.to,direction:direction) case.scale:returnDefineAnimation.scale(.to) case.fade:returnDefineAnimation.fade(.to) case.custom: letanimation=CABasicAnimation(keyPath:"transform.translation.y") animation.fromValue=layer.frame.height animation.toValue=0 returnanimation } } functabBarController(_tabBarController:UITabBarController,shouldSelect viewController:UIViewController)->Bool{ returnanimateTransition(tabBarController,shouldSelect:viewController) } } |
「TransitionableTab」では基本アニメーションとして「move」「scale」「fade」が用意されていますが、「CAAnimation」であれば独自のアニメーションも可能なので今回は「custom」では上に移動して消えていく様なアニメーションを作って見ました。
ちなみに基本の三つは以下の様な動きになります。
「move」
さいごに
「TransitionableTab」は組み込みも簡単ですし、使ってみるだけであれば用意されているアニメーションがありますし、アプリに合わせて独自のアニメーションも簡単に設定できるので是非使って見てください。