簡體   English   中英

iOS中的倒數計時器,根據經過的時間

[英]Countdown Timer in iOS according to elapsed time

我在這里找到了很多有關在iOS中實現倒數計時器的問題和答案,但是還沒有人回答我的問題。

我想要做的是當用戶按下按鈕時,它可以保存他按下按鈕的確切時間,並倒計時6個小時。 我使NSTimer觸發了一種方法,如果計數器達到了將來的結束時間,該方法將每1秒計算一次,並相應地將其顯示在Counter上。

到目前為止,我試圖做的是保存用戶按下按鈕的確切時間,同時找出存儲在名為futureTime的變量中的倒計時結束時間(以毫秒為單位),然后比較兩者(startTime和futureTime)。

- (void)viewDidLoad
{
    [super viewDidLoad];

    sixHours = 21600000;
}


- (IBAction)startTimer:(id)sender {
    [self setStartTime];
    [timer invalidate];
    secondsLeft = sixHours;
    futureTime = self.startTime + sixHours;
    timer = [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(updateCounter:) userInfo:nil repeats:YES];
}

- (void)updateCounter:(NSTimer *)theTimer {
    NSTimeInterval currentTimeInMilliseconds = [[NSDate date] timeIntervalSince1970];
    if (currentTimeInMilliseconds == futureTime) {
        [timer invalidate];
        self.counterLabel.text = @"Done!";
    } else {
        secondsLeft -= 1000;
        self.counterLabel.text = [self formatTimeStamp:secondsLeft];
    }
}

- (void)setStartTime {
    NSTimeInterval currentTimeInMilliseconds = [[NSDate date] timeIntervalSince1970];
    self.startTime = currentTimeInMilliseconds;
}

顯然,它不能很好地工作,並且不准確。

有什么建議么? 還是更好的方法?

謝謝 :)

您只需要一個倒數計時器,在這種情況下,您可以執行以下操作:

@implementation AppDelegate{
    NSTimer *timer;
    NSInteger totalSeconds;
}


-(void)showTime{
    NSLog(@"%ld",totalSeconds--);
    if (totalSeconds==0){
        NSLog(@"6 hours!!! Time over.");
        [timer invalidate];
    }
}


- (IBAction)countDown:(id)sender {
    totalSeconds = 6*60*60; //6 hours * 60 minutes * 60 seconds
    timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(showTime) userInfo:nil repeats:YES];
}

@end

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM