Objective-C: How to animate “Loading…” text on a UILabel

ぐ巨炮叔叔 提交于 2019-12-04 22:07:16

You could easily implement such a behavior yourself – see my example below.

But like trojanfoe suggested, I would rather use a nice library like MBProgressHUD or MarqueeLabel

- (void) updateLoadingLabel;
{
    if(self.loading) {
        if([self.labelLoading.text isEqualToString:@"Loading…"]) {
            self.labelLoading.text = @"Loading";
        } else {
            self.labelLoading.text = [NSString stringWithFormat:@"%@.",self.labelLoading.text];
        }
        [self performSelector:@selector(updateLoadingLabel) withObject:nil afterDelay:1.0]; //each second
    }

}

I thought the animated ellipsis idea was fun. Here is Alexander's example in Swift 3 for mac OS (for iOS just replace ".stringValue" with ".text" I believe):

func animateLoadingLabel()
{
    if loading
    {
        if myLabel.stringValue == "Loading..."
        {
            myLabel.stringValue = "Loading"
        }
        else
        {
            myLabel.stringValue = "\(myLabel.stringValue)."
        }

        perform(#selector(animateLoadingLabel), with: nil, afterDelay: 1)
    }
}

It's called a Marquee. There is one already at Cocoa Controls.

Swift 4.2

You can simply use Timer.

    var timer: Timer?

    titleLabel.text = "Loading ."

    timer = Timer.scheduledTimer(withTimeInterval: 0.55, repeats: true) { (timer) in
        var string: String {
            switch self.titleLabel.text {
            case "Loading .":       return "Loading .."
            case "Loading ..":      return "Loading ..."
            case "Loading ...":     return "Loading ."
            default:                return "Loading"
            }
        }
        self.titleLabel.text = string
    }

    // Stop the timer 
    // timer?.invalidate()

Result

Juan Ledesma Umbracato

Swift 4.2

I just make an extension:

import Foundation
import UIKit

extension UILabel {
func makeLoadingAnimation(text: String) {
    var timer: Timer?

    self.text = "\(text) ."

    timer = Timer.scheduledTimer(withTimeInterval: 0.55, repeats: true) { (timer) in
        var string: String {
            switch self.text {
            case "\(text) .":       return "\(text) .."
            case "\(text) ..":      return "\(text) ..."
            case "\(text) ...":     return "\(text) ."
            default:                return "\(text)"
            }
        }
        self.text = string
    }

    func stopLoadingAnimation() {
         //Stop the timer
         timer?.invalidate()
    }
}
}

And now you can use it like this:

yourLabel.makeLoadingAnimation(text: yourLabel.text)

And in order to stop the timer:

yourLabel.stopLoadingAnimation()
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!