2
2

More than 1 year has passed since last update.

[Swift]タイプライター風にUILabelをアニメーションさせる

Posted at

参考動画

-gdjupqclrgqq32do.gif

このようにUILabelを1文字ずつ表示するアニメーションをする方法を紹介します。

コード

.swift
final class View: UIView {
    @IBOutlet weak var label: UILabel!
    private var timer = Timer()
    private var currentTextCount = 0
    var text: String?

    private func setTimer(_ text: String) {
        timer = Timer.scheduledTimer(timeInterval: 0.075, target: self, selector: #selector(textAnimation(_:)), userInfo: text, repeats: true)
    }

    @objc private func textAnimation(_ timer: Timer) {
        guard let text = timer.userInfo as? String else {
            return
        }
        label.text = String(text.prefix(currentTextCount))
        
        if text.count <= currentTextCount {
            timer.invalidate()
            return
        } 
        currentTextCount += 1
    }
}

解説

textに対して、先頭n文字をTimerで設定した0.075秒間隔で取り出して表示しています。(参考動画はGIFなので遅め)
この処理はUILabelだけではなく、UITextViewでもできます。

他のアクションでアニメーションを止めたい場合はinvalidate()で停止できます。

// タイマーを止める
timer.invalidate()
2
2
0

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
2
2