[英]working with UIProgressView to set progress bar to 30 minutes
我正在處理一個項目,我已經放入了一個進度條,然后設置了一個按鈕以在按下它時啟動進度條。 問題是當你按下開始按鈕時,我希望在 30 分鍾內獲得進度,所以我需要幫助將其設置為 30 分鍾。
這是我設置進度條和開始按鈕的代碼
m文件
- (IBAction)StartButton:(id)sender {
timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(moreProgress)
userInfo:Nil repeats:YES];
[super viewDidLoad];
//progressbar start when button pressed
}
然后我暫時得到了這個
//selector progress time
- (void) moreProgress {
myProgressView.progress += 0.001;
}
我認為這只是一個數學問題。
首先,myProgressView.progress可以采用0.0到1.0之間的值。
當您每秒調用moreProgress時,您需要將其調用1800次,持續30分鍾。 因此,myProgressView.progress應該每秒增加1/1800。
將您的代碼更改為:
- (void) moreProgress {
myProgressView.progress += 1.0/1800.0;
}
希望對您有幫助! :)
1)保存當前時間(例如,您可以將其保存到NSUserDefaults中)。 您可以執行以下操作:
NSUserDefaults *user1 = [NSUserDefaults standardUserDefaults];
NSDate *currentDate = [NSDate date];
[user1 setObject:[NSNumber numberWithDouble:[currentDate timeIntervalSince1970]] forKey:@"time"];
[user1 synchronize];
2)像您一樣安排對函數的調用
timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(moreProgress)
userInfo:Nil repeats:YES];
3)接下來,您需要使用以下內容更新進度視圖狀態:
//selector progress time
- (void) moreProgress {
NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
NSDate *startTime = [NSDate dateWithTimeIntervalSince1970:[[user objectForKey:@"time"]doubleValue]];
NSTimeInterval elapsedTime = [startTime timeIntervalSinceNow];
float progress = (float)elapsed time / 30.0 * 60.0;
myProgressView.progress = progress;
if ((float)elapsedTime / 30 * 60 >= 1)
{
// The timer is end, you should stop it and do what you need
}
}
注意:不安全的期望是
timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(moreProgress)
將每秒觸發一次。 不保證也不精確。
// 這個擴展會幫助你。 我使用過這個擴展,它真的對我有用。
extension UIProgressView {
@available(iOS 10.0, *)
func setAnimatedProgress(progress: Float = 1, duration: Float = 1, completion: (() -> ())? = nil) {
Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { (timer) in
DispatchQueue.main.async {
let current = self.progress
self.setProgress(current+(1/duration), animated: true)
}
if self.progress >= progress {
timer.invalidate()
if completion != nil {
completion!()
}
}
}
}
}
// Just call this extension with your UIProgressView like this
YOUR_PROGRESS_VIEW.setAnimatedProgress(duration: 100) { // Here 100 meaning 10 seconds
debugPrint("Done!")
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.