Objective-C:NSTimer和倒数计时 [英] Objective-C : NSTimer and countdown

查看:78
本文介绍了Objective-C:NSTimer和倒数计时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道我应该了解Apple的NSTimer文档,但我不知道!我也读过很多关于它的问题,但是找不到适合我的情况的问题.好吧,这里是:

I know that I should understand Apple's documentation for NSTimer, but I don't! I have also read a lot of questions about it but can not find one that suites my case. Well here it is:

用户通过文本字段输入小时和分钟.我将它们转换为整数,并在"countDownLabel"中显示它们.

The user enter hour and minutes through textfields. I convert those to integers and display them in a "countDownLabel".

  1. 如何将计数减为零?
  2. 最好显示秒数,这是用户没有导入的秒数,但我想这很难显示.
  3. 有人可以通过按下UIButton来停止此过程吗?

我知道我要问很多...如果有人可以帮助我,我将非常感激!

I know that i am asking a lot...I would be really grateful if someone could help!

int intHourhs;
intHourhs=([textHours.text intValue]);
int intMinutes;
intMinutes=([textMinutes.text intValue]);
int *intSeconds;
intSeconds=0;

NSString *stringTotalTime=[[NSString alloc] initWithFormat:@"%.2i:%.2i:%.2i",intHourhs,intMinutes,intSeconds]; 
[countDownLabel setFont:[UIFont fontWithName:@"DBLCDTempBlack" size:45]];
countDownLabel.text=stringTotalTime;

推荐答案

首先,您应该计算倒计时时间(以秒为单位),并将其放入实例变量(ivar)

First you should calculate what your countdown time is, in seconds and put it in a instance variable (ivar)

NSTimeInterval totalCountdownInterval;

我认为,为了保持良好的准确性(NSTimer触发可能会关闭100毫秒,并且错误会累加起来),您应该记录倒计时的开始日期,并将其放在另一个ivar中:

I think in order to keep good accuracy (NSTimer firing can be off by as much as 100ms and errors will add up) you should record the date at which the countdown started, and put it in another ivar:

NSDate* startDate = [NSDate date];

然后,您可以让计时器以固定的间隔(此处为1秒)触发,从而在您的类上反复调用方法

Then you can have a timer firing at regular (here 1 second) intervals calling a method on your class repeatedly

NSTimer* timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(checkCountdown:) userInfo:nil repeats:YES];

然后通过这种方法,将经过的时间与总的倒计时时间进行比较,并更新界面

And in that method you check the elapsed time against the total countdown time and update the interface

-(void) checkCountdown:(NSTimer*)_timer {

    NSTimeInterval elapsedTime = [[NSDate date] timeIntervalSinceDate:startDate];

    NSTimeInterval remainingTime = totalCountdownInterval - elapsedTime;

    if (remainingTime <= 0.0) {
        [_timer invalidate];
    }

    /* update the interface by converting remainingTime (which is in seconds)
       to seconds, minutes, hours */

}

这篇关于Objective-C:NSTimer和倒数计时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆