Letter by letter animation for UILabel?

Viewed 19288

Is there a way to animate the text displayed by UILabel. I want it to show the text value character by character.

Help me with this folks

15 Answers

Update: 2019, swift 5

It works! Just copy paste my answer & see your result

Also create an @IBOutlet weak var titleLabel: UILabel! before the viewDidLoad()

override func viewDidLoad() {
    super.viewDidLoad()

    titleLabel.text = ""
    let titleText = "⚡️Please Vote my answer"
    var charIndex = 0.0
    for letter in titleText {
        Timer.scheduledTimer(withTimeInterval: 0.1 * charIndex, repeats: false) { (timer) in
            self.titleLabel.text?.append(letter)
        }
         charIndex += 1
    }

   }

SwiftUI + Combine example:

struct TypingText: View {
    typealias ConnectablePublisher = Publishers.Autoconnect<Timer.TimerPublisher>
    private let text: String
    private let timer: ConnectablePublisher
    private let alignment: Alignment

    @State private var visibleChars: Int = 0

    var body: some View {
        ZStack(alignment: self.alignment) {
            Text(self.text).hidden() // fixes the alignment in position
            Text(String(self.text.dropLast(text.count - visibleChars))).onReceive(timer) { _ in
                if self.visibleChars < self.text.count {
                    self.visibleChars += 1
                }
            }
        }
    }

    init(text: String) {
        self.init(text: text, typeInterval: 0.05, alignment: .leading)
    }

    init(text: String, typeInterval: TimeInterval, alignment: Alignment) {
        self.text = text
        self.alignment = alignment
        self.timer = Timer.TimerPublisher(interval: typeInterval, runLoop: .main, mode: .common).autoconnect()
    }
}

I know it is too late for the answer but just in case for someone who is looking for the typing animation in UITextView too. I wrote a small library Github for Swift 4. You can set the callback when animation is finished.

@IBOutlet weak var textview:TypingLetterUITextView!
textview.typeText(message, typingSpeedPerChar: 0.1, completeCallback:{
       // complete action after finished typing }

Also, I have UILabel extension for typing animation.

label.typeText(message, typingSpeedPerChar: 0.1, didResetContent = true, completeCallback:{
       // complete action after finished typing }

I wrote a small open source lib to do it. I built it with NSAttributedString such that the label won't resize during the animation. It also supports typing sounds and curser animation

Check out here:

https://github.com/ansonyao/AYTypeWriter

Related