カテゴリー: iOS

[Swift]タブの切り替え時にアニメーションが簡単に実装できる「TransitionableTab」

はじめに

こんにちは、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」

「scale」

「fade」

さいごに

「TransitionableTab」は組み込みも簡単ですし、使ってみるだけであれば用意されているアニメーションがありますし、アプリに合わせて独自のアニメーションも簡単に設定できるので是非使って見てください。

nukky

シェア
執筆者:
nukky
タグ: Swift

最近の投稿

フロントエンドで動画デコレーション&レンダリング

はじめに 今回は、以下のように…

3週間 前

Goのクエリビルダー goqu を使ってみる

はじめに 最近携わっているとあ…

1か月 前

【Xcode15】プライバシーマニフェスト対応に備えて

はじめに こんにちは、suzu…

2か月 前

FSMを使った状態管理をGoで実装する

はじめに 一般的なアプリケーシ…

3か月 前