打字机效果文本动画

syqv5f0l  于 2022-10-23  发布在  Swift
关注(0)|答案(4)|浏览(397)

我正在尝试用UILabel创建打字机动画效果,但找不到任何答案。UILabel是要使用的正确对象吗?我希望文本打印到屏幕上的字符串数组,如“正在登录...正在打开文件夹...正在重新启动系统..”我应该提一下,我是编程新手,我已经尝试过搜索文档和API参考,但没有成功。如果值得一提的是,我目前正在学习SWIFT

ivqmmu1c

ivqmmu1c1#

基于这个答案: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")
2hh7jdfx

2hh7jdfx2#

更新: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.
    }
}
pxyaymoc

pxyaymoc3#

我已经编写了一个名为CLTypingLabel的UILabel子类,可在GitHub上获得。这应该能做你想做的事。
安装CocoaPods后,将如下代码添加到Podfile中以使用它:

pod 'CLTypingLabel'

示例代码

将标签的类别从UILabel更改为CLTypingLabel;

@IBOutlet weak var myTypeWriterLabel: CLTypingLabel!

在运行时,设置标签文本将自动触发动画:

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附带的样例项目

hpcdzsge

hpcdzsge4#

我使用定时器的打字机效果动画版本:

var text = "text"

    _ = Timer.scheduledTimer(
        withTimeInterval: 0.1,
        repeats: true
    ) { [weak self] timer in
        let char = text.removeFirst()

        self?.yourLabel.text?.append(char.description)

        if text.isEmpty {
            timer.invalidate()
        }
    }

相关问题