按秒倒数计时器

Posted

技术标签:

【中文标题】按秒倒数计时器【英文标题】:push seconds to countdown timer 【发布时间】:2012-06-27 20:20:20 【问题描述】:

我创建了一个显示在标签上的倒数计时器,现在我想添加一个功能,当用户按下按钮时,它将向倒数计时器添加 30 秒。 我试图自己做,但我没有成功(我遇到了一个错误,有一次它停止了我的计时器)我该怎么做? 这是我的代码:

-(IBAction)start:(id)sender

    timer = [NSTimer scheduledTimerWithTimeInterval:.01 target:self     selector:@selector(updateTimer:) userInfo:nil repeats:YES];



-(void)updateTimer:(NSTimer *)timer

    currentTime -= 10 ;
    [self populateLabelwithTime:currentTime];

    if(currentTime <=0)
    
        [timer invalidate];
        //some code when countdown reach to 00:00:00
    




- (void)populateLabelwithTime:(int)milliseconds 
    seconds = milliseconds/1000;
    minutes = seconds / 60;


    seconds -= minutes * 60;

    NSString * countdownText = [NSString stringWithFormat:@"%@%02d:%02d:%02d", (milliseconds<0?@"-":@""), minutes, seconds,milliseconds%1000];
    countdownLabel.text = countdownText;



-(IBAction)addTime:(id)sender

    timer = [NSTimer scheduledTimerWithTimeInterval:.01 target:self selector:@selector(addToCurrent:) userInfo:nil repeats:YES];


-(void) addToCurrent:(NSTimer *)timerb;

    seconds +=10;
    [self populateLabelWithTime:seconds];


- (void)viewDidLoad

    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    currentTime = 2700;


谢谢!

【问题讨论】:

准确地列出问题所在以及您遇到的错误是很有帮助的。 -(IBAction)addTime:(id)sender currentTime += 30000; 【参考方案1】:

无需在每次单击按钮时重新创建计时器。此外,在我看来,当您尝试将 30 秒添加回计时器时,您不小心修改了秒数而不是 currentTime。

-(IBAction)addTime:(id)sender

    currentTime += 30000;
    [self populateLabelWithTime:currentTime];

【讨论】:

以上是关于按秒倒数计时器的主要内容,如果未能解决你的问题,请参考以下文章

为啥倒数计时器突然执行得很快?

带有 CircularProgressIndicator 的倒数计时器

如何检查可观察倒数计时器是不是已完成?

Flutter:当倒数计时器达到 0 时执行动作

倒数计时器停止在后台运行

React 中的倒数计时器