Search code examples
iosswiftanimationuiviewuilabel

How do I make a UILabel with dynamically changing and looping text?


I want to make a label that's text changes from "Loading" -> "Loading." ->"Loading.." -> "Loading..." dynamically and for as long as that label exists.

So I just created a label and added a function that I call called animateDots that just keeps calling itself. I had it done using UIView.animateWithDuration() and every completion block calls another animateWithDuration() until it just calls animateDots() and so on. But that didn't work because the text in a UILabel isn't animatable so it just animates all four labels really fast. I want it to be slow.

I tried UIView.preformWithoutAnimation and I also tried UIView.beginAnimations but I can't recall animateDots() without causing the app to crash. I have no idea what else to try

Edit: Here's how I solved it thanks to @7vikram7 's suggestion.

I created the timer right after I initialize the label, and the timer repeats. Every time the timer finishes a loop, it runs a selector, in this case animateDots, which changes the text. In Code:

Add this whenever you want to start the animation process:

loading = UILabel(frame: CGRectMake(0,0,80,50))
loading.text = "Loading"
let timer = NSTimer.scheduledTimerWithTimeInterval(0.5, target: self, selector:
            #selector(LoadingCell.animateDots), userInfo: nil, repeats: true)
        timer.fire()

Then add this function:

func animateDots() {
        switch (loading.text!) {
        case "Loading...":
            loading.text = "Loading"
        case "Loading":
            loading.text = "Loading."
        case "Loading.":
            loading.text = "Loading.."
        case "Loading..":
            loading.text = "Loading..."
        default:
            loading.text = "Loading"
        }
    }

Solution

  • You can use NSTimer. Schedule a timer with interval of 2 or 3 seconds which repeats.

    https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSTimer_Class/