Swift UILabel, letter animation
Here is a snippet to animate the display of a UILabel as if you were typing text on the keyboard ...

Here is a code snippet to animate a UILabel display as if you were typing text on the keyboard, letter by letter. It is a swift extension to be used by simply call as a function.

I also advise you for this kind of thing to create a file by extension, UILabel.swift, UIImage.swift .... as we started to do in the swift stack.
extension UILabel {
/**
* @desc anime text like if someone write it
* @param {String} text,
* @param {TimeInterval} characterDelay,
*/
func animate(newText: String, interval: TimeInterval = 0.07, lineSpacing: CGFloat = 1.2, letterSpacing: CGFloat = 1.1) {
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineSpacing = 1.2
paragraphStyle.lineHeightMultiple = 1.2
paragraphStyle.alignment = .center
var pause: TimeInterval = 0
self.text = ""
var charIndex = 0.0
for letter in newText {
Timer.scheduledTimer(withTimeInterval: interval * charIndex + pause, repeats: false) { (_) in
self.text?.append(letter)
let attributedString = NSMutableAttributedString(string: self.text ?? "")
attributedString.addAttribute(NSAttributedString.Key.paragraphStyle, value: paragraphStyle, range: NSRange(location: 0, length: attributedString.length))
attributedString.addAttribute(NSAttributedString.Key.kern, value: letterSpacing, range: NSRange(location: 0, length: attributedString.length - 1))
self.attributedText = attributedString
}
charIndex += 1
if(letter == "," || letter == ".") {
pause += 0.5
}
} }
}
After a rush of code lately, I will be able to resume writing more regularly on the blog. I will try to share a lot of Snippets of this style, always useful to give a little more life to a project, but also compatible with our stacks.