[Solved] Animate text inside label – New word appears as if reading [closed]


As @SeyyedParsaNeshaei says, there is another answer that gives a “marquee” type scrolling, however, if what you want (as you say) is one word at a time, consider the following little sketch, which will run in Playground. It basically sets up a timer that changes the text of a UILabel one word at a time.

import UIKit
import PlaygroundSupport
PlaygroundPage.current.needsIndefiniteExecution = true

class MyVC: UIViewController {
    var tickTock: Int = 0
    var myString = ""
    var label: UILabel!
    // Following block only needed in Playground. 
    // Normally you would wire up the label in IB.
    { didSet { self.view.addSubview(self.label) } }

    override func viewDidLoad() {
        // This next line only necessary in Playground. 
        // Normally, the view would be set from the StoryBoard
        self.view = UIView(frame: CGRect(origin: .zero, size: CGSize(width: 100, height: 60)))
        super.viewDidLoad()
        // "1" in the next line is the inter-word interval in seconds.
        // Obviously you wouldn't hard-wire this.
        let _ = Timer.scheduledTimer(withTimeInterval: 1, repeats: true, block: { _ in
            let words = self.myString.components(separatedBy: " ")
            var word = "<Nothing>"
            if words.count > 0 {
                self.tickTock = self.tickTock % words.count
                if !words[self.tickTock].isEmpty {
                    word = words[self.tickTock]
                }
            }
            self.label?.text = word
            self.tickTock += 1
        })
    }
}
// Playground code to test:
let label = UILabel(frame: CGRect(x: 0, y: 0, width: 100, height: 60))
label.textColor = .yellow
label.textAlignment = .center
let myVC = MyVC()
myVC.myString = "May the source be with you"
myVC.label = label

PlaygroundPage.current.liveView = myVC.view

To see the animation, select “View>Assistant Editor>Show Assistant Editor” from the Playground menu.

For a fuller solution, you probably want to look at components(separatedBy: CharactersSet) rather than components(separatedBy: String), which I’ve used – it depends on how you want to present punctuation…

3

solved Animate text inside label – New word appears as if reading [closed]