LoginSignup
1

More than 3 years have passed since last update.

CATransitionはアニメーションさせたいとき毎回追加する必要がある

Last updated at Posted at 2019-04-03

UILabelでテキストを変更した際に遷移アニメーションをさせたくて、以下のようなクラスを作成しました。

class AnimatedLabel: UILabel {
    override init(frame: CGRect) {
        super.init(frame: frame)
        setup()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        setup()
    }

    private func setup() {
        let animation = CATransition()
        animation.type = .reveal
        animation.subtype = .fromBottom
        animation.timingFunction = CAMediaTimingFunction(name: .easeOut)
        animation.duration = 1
        layer.add(animation, forKey: "transition")
    }
}

これでテキストを変更するたびにアニメーションが実行されるだろうと思っていたのですが、アニメーションが実行されませんでした。

テキストを変更するコードの直前でアニメーションオブジェクトを確認したところ、nilとなっていました。

print(label.layer.animation(forKey: "transition"))  // nil

ドキュメントで確認ができていないのですが、一度アニメーションを実行したらオブジェクトは削除されてしまうのでしょうか。

仕方ないのでアニメーションさせたいときは以下のように毎回CATransitionオブジェクトを作ってレイヤーに追加するようにしました。

let animation = CATransition()
animation.type = .reveal
animation.subtype = .fromBottom
animation.timingFunction = CAMediaTimingFunction(name: .easeOut)
animation.duration = 1
label.layer.add(animation, forKey: nil)

label.text = "Changed!"

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
1