问题
In my app I need to display a "Loading" text in an UILabel, repeatedly as follows:
Loading Loading. Loading.. Loading... Loading Loading. Loading.. Loading...
How can I do it? Any suggestion, please?
回答1:
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
}
}
回答2:
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)
}
}
回答3:
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
回答4:
It's called a Marquee. There is one already at Cocoa Controls.
回答5:
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()
来源:https://stackoverflow.com/questions/24359730/objective-c-how-to-animate-loading-text-on-a-uilabel