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!"