倒计时计时器 - iPhone

5
我想显示倒计时计时器。我有开始日期和结束日期。我需要显示剩余时间,如下:
天:小时:分钟:秒
我该怎么做?

https://dev59.com/N1LTa4cB1Zd3GeqPcJ4H - Ramaraj T
我的代码已经实现了,它运行得很好。我只是添加了输出,请检查一下。 - Nitin Gohel
3个回答

18

你可以像下面的代码一样设置倒计时:

 -(void) viewWillAppear:(BOOL)animated
 {
 timer = [NSTimer scheduledTimerWithTimeInterval: 1.0 target:self selector:@selector(updateCountdown) userInfo:nil repeats: YES];
 }

 -(void) updateCountdown 
 {

NSString *dateString = @"14-12-2012";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];

[dateFormatter setDateFormat:@"dd-MM-yyyy"];
NSDate *dateFromString = [[NSDate alloc] init];
// voila!
dateFromString = [dateFormatter dateFromString:dateString];


NSDate *now = [NSDate date];
NSCalendar *calendar = [NSCalendar currentCalendar];



NSDateComponents *componentsHours = [calendar components:NSHourCalendarUnit fromDate:now];
NSDateComponents *componentMint = [calendar components:NSMinuteCalendarUnit fromDate:now];    
NSDateComponents *componentSec = [calendar components:NSSecondCalendarUnit fromDate:now];        


NSCalendar *gregorianCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *componentsDaysDiff = [gregorianCalendar components:NSDayCalendarUnit
                                                            fromDate:now
                                                              toDate:dateFromString
                                                             options:0];



lblDaysSetting.text=[NSString stringWithFormat:@"%02d",componentsDaysDiff.day];
lblHouresSetting.text=[NSString stringWithFormat:@"%02d",(24-componentsHours.hour)];    
lblMinitSetting.text=[NSString stringWithFormat:@"%02d",(60-componentMint.minute)];  
lblSecSetting.text=[NSString stringWithFormat:@"%02d",(60-componentSec.second)];  



 }

现在只需设置您的逻辑

它的代码输出如下所示:

enter image description here


从后台返回后,它能正常工作吗? - Dev
当我最小化我的应用程序时,倒计时时钟会停止还是继续在后台运行? - Dev
是的,当你重新打开应用时,它会运行并调用ViewwillApear方法,因此它将以当前时间运行,而不是从头开始。但是,如果你设置了静态的启动时间,它将从该时间开始运行。 - Nitin Gohel

5

以下是.h文件的代码:

@interface UIMyContoller : UIViewController {

NSTimer *timer;
IBOutlet UILabel *myCounterLabel;
}

@property (nonatomic, retain) UILabel *myCounterLabel;
-(void)updateCounter:(NSTimer *)theTimer;
-(void)countdownTimer;

@end

以下是 .m 文件的代码:

@implementation UIMyController
@synthesize myCounterLabel;

int hours, minutes, seconds;
int secondsLeft;

- (void)viewDidLoad {
[super viewDidLoad];

secondsLeft = 16925;
[self countdownTimer];
}

- (void)updateCounter:(NSTimer *)theTimer {
if(secondsLeft > 0 ){
    secondsLeft -- ;
    hours = secondsLeft / 3600;
    minutes = (secondsLeft % 3600) / 60;
    seconds = (secondsLeft %3600) % 60;
    myCounterLabel.text = [NSString stringWithFormat:@"%02d:%02d:%02d", hours, minutes, seconds];
}
else{
    secondsLeft = 16925;
}
}

-(void)countdownTimer{

secondsLeft = hours = minutes = seconds = 0;
if([timer isValid])
{
    [timer release];
}
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];  
timer = [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(updateCounter:) userInfo:nil repeats:YES];
[pool release];
}

希望这可以帮到你。愉快编码。
阿德里安

2
我建议使用以下方法获取从开始日期到结束日期的时间组件。
这种方法比手动递减3个整数变量(小时,分钟和秒)更加优雅,因为这样做意味着你必须手动检查何时秒钟归零,必须手动将分钟重置为59等等。我曾经尝试过这种方法,效果不太好。
此外,当你最小化应用程序时,倒计时时钟会停止。如果你手动递减3个整数(小时,分钟和秒)来进行倒计时,最小化你的应用程序会导致倒计时出错。
由于这种方法自动计算两个日期之间的差异,即使应用程序从后台最小化状态返回,它也会自动重新计算剩余时间,而无需任何额外的代码。
-(void)viewDidLoad
{
    // instantiate a calendar object.
    gregorianCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];

    countDownTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(updateClock:) userInfo:nil repeats:YES];
    [countDownTimer fire];
}

-(void)updateClock:(NSTimer *)timer
{
    countDownDateFormatter = [[NSDateFormatter alloc] init];
    [countDownDateFormatter setDateFormat:@"hh:mm:ss"];

    NSDate *now = [NSDate date];

    NSDateComponents *comp = [gregorianCalendar components:NSHourCalendarUnit|NSMinuteCalendarUnit|NSSecondCalendarUnit 
                                                  fromDate:now
                                                    toDate:countDownEndDate 
                                                   options:0];

    NSString *strTimeRemaining = nil;

    // if date have not expired
    if([now compare:countDownEndDate] == NSOrderedAscending)
    {
        strTimeRemaining = [[NSString alloc] initWithFormat:@"%02d:%02d:%02d", [comp hour],  [comp minute], [comp second]];
    }
    else 
    {
        // time has expired, set time to 00:00 and set boolean flag to no
        strTimeRemaining = [[NSString alloc] initWithString:@"00:00:00"];

        [countDownTimer invalidate];
        countDownTimer = nil;
    }

    lblCountDown.text = strTimeRemaining;

    [countDownDateFormatter release];
    [strTimeRemaining release];
}

这里的gregorianCalendar是什么? - Dev
gregorianCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];在头文件(.h文件)中声明这个变量为NSCalendar *gregorianCalendar,并在viewDidLoad中实例化它。我已经更新了我的答案。 - Zhang

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接