こんにちは、nukkyです。
今回は、UITabBarControllerの切り替え時にアニメーションを実装できるライブラリ「TransitionableTab」を紹介したいと思います。
今回もおなじみCarthageを使用します。
Cartfileにこちらを記述してください。
github "Interactive-Studio/TransitionableTab" ~> 0.1.2
そうしたら、以下のコマンドでビルドしてください。
carthage update --platform iOS
まずは以下のインポートを行ってください。
import UIKit import TransitionableTab
enumでアニメーションのタイプを定義しておきます。
「TransitionableTab」では基本的なアニメーションとして「move」「scale」「fade」が用意されています各アニメーションの動きについては後ほど
enum Type: String { case move case fade case scale case custom static var all: [Type] = [.move, .scale, .fade, .custom] }
UITabBarControllerでクラスを作成します。
アニメーション選択変数を用意しておき、viewDidLoadでdelegateにselfを設定します。
class TabBarController: UITabBarController { // アニメーション設定用 var type: Type = .custom override func viewDidLoad() { super.viewDidLoad() self.delegate = self } }
extensionで「TransitionableTab」のプロトコルを継承します。
extension TabBarController: TransitionableTab { func fromTransitionAnimation(layer: CALayer, direction: Direction) -> CAAnimation { switch type { case .move: return DefineAnimation.move(.from, direction: direction) case .scale: return DefineAnimation.scale(.from) case .fade: return DefineAnimation.fade(.from) case .custom: let animation = CABasicAnimation(keyPath: "transform.translation.y") animation.fromValue = 0 animation.toValue = -layer.frame.height return animation } } func toTransitionAnimation(layer: CALayer, direction: Direction) -> CAAnimation { switch type { case .move: return DefineAnimation.move(.to, direction: direction) case .scale: return DefineAnimation.scale(.to) case .fade: return DefineAnimation.fade(.to) case .custom: let animation = CABasicAnimation(keyPath: "transform.translation.y") animation.fromValue = layer.frame.height animation.toValue = 0 return animation } } func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool { return animateTransition(tabBarController, shouldSelect: viewController) } }
「TransitionableTab」では基本アニメーションとして「move」「scale」「fade」が用意されていますが、「CAAnimation」であれば独自のアニメーションも可能なので今回は「custom」では上に移動して消えていく様なアニメーションを作って見ました。
ちなみに基本の三つは以下の様な動きになります。
「move」
「TransitionableTab」は組み込みも簡単ですし、使ってみるだけであれば用意されているアニメーションがありますし、アプリに合わせて独自のアニメーションも簡単に設定できるので是非使って見てください。