参考動画
このように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()