Objective-C:如何在UILabel上为“加载...”文本设置动画

问题描述 投票:-2回答:5

在我的应用程序中,我需要在UILabel中显示“正在加载”文本,重复如下:

正在加载。正在加载......正在加载......正在加载Loading .. Loading ...

我该怎么做?请问有什么建议吗?

iphone objective-c uilabel uiviewanimation
5个回答
2
投票

您可以自己轻松实现此类行为 - 请参阅下面的示例。

但是像trojanfoe建议的那样,我宁愿使用像MBProgressHUDMarqueeLabel这样的好库

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

}

2
投票

我认为动画省略号的想法很有趣。这是亚历山大在Swift 3中用于mac OS的示例(对于iOS,只需将“.stringValue”替换为“.text”我相信):

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

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

1
投票

它被称为Marquee。有一个已经在Cocoa Controls


1
投票

Swift 4.2

你可以简单地使用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 Screen


1
投票

Swift 4.2

我只是做了一个扩展:

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

现在你可以像这样使用它:

yourLabel.makeLoadingAnimation(text: yourLabel.text)

并且为了停止计时器:

yourLabel.stopLoadingAnimation()
© www.soinside.com 2019 - 2024. All rights reserved.