打字机效果文字动画

Typewriter effect text animation

我正在尝试使用 UILabel 创建打字机动画效果,但找不到任何答案。 UILabel 是要使用的正确对象吗?我希望文本将字符串数组打印到屏幕上,例如 "Logging in... Opening Folder... Rebooting system.." 等。我应该提到我是编码新手,我已经尝试搜索文档和 API 参考但没有运气.我目前正在学习 SWIFT 如果那值得一提

更新:Xcode 7.0 GM • Swift 2.0

import UIKit

class ViewController: UIViewController {
    @IBOutlet weak var myTypeWriter: UITextField!
    let myText = Array("Hello World !!!".characters)
    var myCounter = 0
    var timer:NSTimer?
    func fireTimer(){
        timer = NSTimer.scheduledTimerWithTimeInterval(0.5, target: self, selector: "typeLetter", userInfo: nil, repeats: true)
    }
    func typeLetter(){
        if myCounter < myText.count {
            myTypeWriter.text = myTypeWriter.text! + String(myText[myCounter])
            let randomInterval = Double((arc4random_uniform(8)+1))/20
            timer?.invalidate()
            timer = NSTimer.scheduledTimerWithTimeInterval(randomInterval, target: self, selector: "typeLetter", userInfo: nil, repeats: false)
        } else {
            timer?.invalidate()
        }
        myCounter++
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        fireTimer()
        // Do any additional setup after loading the view, typically from a nib.
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}

我写了一个名为 CLTypingLabel 的 UILabel 的子class,可以在 GitHub 上找到。这应该可以满足您的需求。

安装 CocoaPods 后,将以下内容添加到您的 Podfile 中以使用它:

pod 'CLTypingLabel'

示例代码

将标签的 class 从 UILabel 更改为 CLTypingLabel;

@IBOutlet weak var myTypeWriterLabel: CLTypingLabel!

运行时设置label的文字会自动触发动画:

myTypeWriterLabel.text = "This is a demo of typing label animation..."

您可以自定义每个字符之间的时间间隔:

myTypeWriterLabel.charInterval = 0.08 //optional, default is 0.1

您可以随时暂停打字动画:

myTypeWriterLabel.pauseTyping() //this will pause the typing animation
myTypeWriterLabel.continueTyping() //this will continue paused typing animation

还有一个示例项目cocoapods

基于这个答案: Letter by letter animation for UILabel?

我已将其更新为 Swift 4 并使用 DispatchWorkItem 解决了 CPU 动画问题,以便创建队列。

Swift 4

extension UILabel {
    func setTextWithTypeAnimation(typedText: String, characterDelay: TimeInterval = 5.0) {
        text = ""
        var writingTask: DispatchWorkItem?
        writingTask = DispatchWorkItem { [weak weakSelf = self] in
            for character in typedText {
                DispatchQueue.main.async {
                    weakSelf?.text!.append(character)
                }
                Thread.sleep(forTimeInterval: characterDelay/100)
            }
        }
        
        if let task = writingTask {
            let queue = DispatchQueue(label: "typespeed", qos: DispatchQoS.userInteractive)
            queue.asyncAfter(deadline: .now() + 0.05, execute: task)
        }
    }
    
}

用法

label.setTextWithTypeAnimation(typedText: text, characterDelay:  10) //less delay is faster

Swift 5

func setTyping(text: String, characterDelay: TimeInterval = 5.0) {
  self.text = ""
    
  let writingTask = DispatchWorkItem { [weak self] in
    text.forEach { char in
      DispatchQueue.main.async {
        self?.text?.append(char)
      }
      Thread.sleep(forTimeInterval: characterDelay/100)
    }
  }
    
  let queue: DispatchQueue = .init(label: "typespeed", qos: .userInteractive)
  queue.asyncAfter(deadline: .now() + 0.05, execute: writingTask)
}

用法

label.setTyping(text: "Your text")