Typewriter effect text animation

后端 未结 3 1122
悲哀的现实
悲哀的现实 2020-12-03 09:19

I\'m trying to create a typewriter animation effect with a UILabel, but can\'t find any answers. Is the UILabel the correct object to use? I want the text to print to the sc

3条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-03 09:56

    Based on this Answer: Letter by letter animation for UILabel?

    I've updated it to Swift 4 and solved the CPU animation problem with DispatchWorkItem in order to create a queue.

    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)
            }
        }
    
    }
    

    Usage

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

提交回复
热议问题