Изучение Swift: эффект анимации ввода для текста метки

В этой статье блога мы рассмотрим различные методы создания эффекта анимации набора текста для текста метки в Swift. Для достижения этого эффекта мы воспользуемся возможностями Core Animation и UIKit. Давайте погрузимся!

Метод 1: использование CADisplayLink

import UIKit
class TypingLabel: UILabel {
    private var displayLink: CADisplayLink?
    private var attributedTextToType: NSAttributedString?
    private var currentCharacterIndex: Int = 0

    func startTypingAnimation(with text: NSAttributedString) {
        attributedTextToType = text
        currentCharacterIndex = 0
        displayLink = CADisplayLink(target: self, selector: #selector(updateText))
        displayLink?.add(to: .current, forMode: .common)
    }

    @objc private func updateText() {
        guard let attributedText = attributedTextToType else { return }

        if currentCharacterIndex <= attributedText.length {
            self.attributedText = attributedText.attributedSubstring(from: NSRange(location: 0, length: currentCharacterIndex))
            currentCharacterIndex += 1
        } else {
            displayLink?.invalidate()
            displayLink = nil
        }
    }
}

Метод 2: использование UIView.animateKeyframes

import UIKit
class TypingLabel: UILabel {
    private var attributedTextToType: NSAttributedString?
    private var currentCharacterIndex: Int = 0

    func startTypingAnimation(with text: NSAttributedString) {
        attributedTextToType = text
        currentCharacterIndex = 0

        UIView.animateKeyframes(withDuration: 1.0, delay: 0, options: .calculationModeLinear, animations: {
            for i in 0..<text.length {
                UIView.addKeyframe(withRelativeStartTime: Double(i)/Double(text.length), relativeDuration: 1.0/Double(text.length), animations: {
                    self.attributedText = text.attributedSubstring(from: NSRange(location: 0, length: i+1))
                })
            }
        }, completion: nil)
    }
}

Метод 3: использование таймера

import UIKit
class TypingLabel: UILabel {
    private var timer: Timer?
    private var attributedTextToType: NSAttributedString?
    private var currentCharacterIndex: Int = 0

    func startTypingAnimation(with text: NSAttributedString) {
        attributedTextToType = text
        currentCharacterIndex = 0

        timer = Timer.scheduledTimer(timeInterval: 0.1, target: self, selector: #selector(updateText), userInfo: nil, repeats: true)
    }

    @objc private func updateText() {
        guard let attributedText = attributedTextToType else { return }

        if currentCharacterIndex <= attributedText.length {
            self.attributedText = attributedText.attributedSubstring(from: NSRange(location: 0, length: currentCharacterIndex))
            currentCharacterIndex += 1
        } else {
            timer?.invalidate()
            timer = nil
        }
    }
}

В этой статье мы рассмотрели три различных метода создания эффекта анимации набора текста для текста метки в Swift. Для достижения этого эффекта мы использовали Core Animation и UIKit. Первый метод использовал CADisplayLink, второй метод использовал UIView.animateKeyframes, а третий метод использовал Timer. Вы можете выбрать метод, который лучше всего соответствует вашим требованиям, и интегрировать его в свои проекты Swift, чтобы добавить к меткам привлекательную анимацию набора текста.

Не забывайте экспериментировать и настраивать эти методы в соответствии со своими потребностями. Приятного кодирования!