Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
118 views
in Technique[技术] by (71.8m points)

ios - Animation typing words in label. Swift

i'm trying to make animation typing words in label. With short text everything works good, but if i put a bit longer it starts writing by parts of the word, not by one letter. whats wrong in my code? And how to fix it?

extension UILabel {
    func animate(newText: String, characterDelay: TimeInterval) {
        DispatchQueue.main.async {
            self.text = ""
            for (index, character) in newText.enumerated() {
                DispatchQueue.main.asyncAfter(deadline: .now() + characterDelay * Double(index)) {
                    self.text?.append(character)
                    self.fadeTransition(0.2)
                }
            }
        }
    }
}

extension UIView {
    
    func fadeTransition(_ duration:CFTimeInterval) {
        let animation = CATransition()
        animation.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeInEaseOut)
        animation.type = CATransitionType.fade
        animation.duration = duration
        layer.add(animation, forKey: CATransitionType.fade.rawValue)
    }
}

next in viewDidLoad I called func:

override func viewDidLoad() {
        super.viewDidLoad()
        Label.animate(newText: """
Здесь много текста.
""", characterDelay: 0.1)
}
question from:https://stackoverflow.com/questions/65836836/animation-typing-words-in-label-swift

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

find another answer:

extension UILabel {
    func animation(typing value: String, duration: Double){
        for char in value {
            self.text?.append(char)
            RunLoop.current.run(until: Date() + duration)
        }
    }
}

and called in viewDidAppear, not in viewDidLoad

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)

    Label.text = ""
    Label.animation(typing: "Здесь много всякого разного текста.", duration: 0.1)
}

i don't know is it right or not, but it works )


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...