计时器在iOS中使用UIDatePicker倒计时

时间:2013-02-26 13:23:03

标签: ios cocoa-touch uidatepicker

在我的应用中,我允许用户使用UIDatePicker's CountDownTimer设置倒数计时器。

我有一个UILabel来显示计数时间当用户从CountDownTimer中选择时间时,我想显示在CoutDownTimer中选择的用户如下图所示。

enter image description here

因此我使用以下代码

检索用户从CountDownTimer中选择的计数时间
self.dateFormatter = [[NSDateFormatter alloc] init];
[self.dateFormatter setDateFormat:@"HH:mm:ss"];

self.sleepTimer = [NSTimer timerWithTimeInterval:1.00 target:self selector:@selector(timerFired:) userInfo:nil repeats:NO];

当它到达00:00时,我想发射一个事件。

我不知道如何减少每一秒倒计时。

感谢您的帮助。

3 个答案:

答案 0 :(得分:3)

您可以通过以下方式完成:

[NSTimer timerWithTimeInterval:1.00 target:self selector:@selector(decrementByOne:) userInfo:nil repeats:YES];

答案 1 :(得分:2)

countDownDuration的{​​{1}}属性(值以秒为单位)保存在名为UIDatePicker的实例变量中。

secondsLeft

这将每秒调用您的方法self.sleepTimer = [NSTimer scheduledTimerWithTimeInterval:1.00 target:self selector:@selector(timerFired:) userInfo:nil repeats:YES]; 。将timerFired:减去1.用剩余时间更新secondsLeft(格式化时将秒数格式化为hh:mm:ss - See this question)。验证倒计时是否还有剩余时间,并在倒数完成后采取适当的措施(UILabel)。

记得在倒计时完成后清理;

secondsLeft <= 0

答案 2 :(得分:0)

记下您的日期,将其保存到房产中并查看NSDates

– dateByAddingTimeInterval:

所以,如果你这样做

[self.date dateByAddingTimeInterval:-1];

你将把你的日期递减1秒。 之后,使用新计算的日期更新UI。

此外,您可以将所有代码打包在一个函数中,并通过调用:

执行此函数
performSelector:withObject:afterDelay: 
相关问题