[英]Objective-C: How to animate “Loading…” text on a UILabel
在我的應用程序中,我需要在UILabel中重復顯示“正在加載”文本,如下所示:
正在加載正在加載。 正在加載..正在加載...正在加載正在加載。 正在加載..正在加載...
我該怎么做? 有什么建議嗎?
您可以輕松地自己實現這種行為–請參閱下面的示例。
但就像trojanfoe建議的那樣,我寧願使用MBProgressHUD或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
}
}
我認為動畫省略號的想法很有趣。 這是Alexander 3在Mac OS的Swift 3中的示例(對於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)
}
}
這就是字幕 。 可可控制公司已經有一個。
斯威夫特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()
結果
斯威夫特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()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.