iPhone NSDate 应用举例:倒计时

这周帮其他项目组的同仁完善world cup planner 2010 (一款关于世界杯的应用, 在 iTune uk 上)其中有个世界杯开幕倒计时功能,在这把代码共享下。 效果图:

 

 

原理很简单:

1. 设定结束的时间

2. 计算此时间到当前时间所剩的秒数

3. 将此秒数转化为所要显示的天,小时,分钟和秒。

4. 利用NSTimer, 每间隔1秒显示一次。

 

NSDate 用起来总没有这么舒服,反正cocoa的东西都挺别扭。可能是我初学吧。

1. 利用NSDateComponents 设定具体某一时间。

// init endDate to 15:00 11/06/2010NSDateComponents *components = [[NSDateComponents alloc] init];[components setHour:15];[components setDay:11];[components setMonth:6];[components setYear:2010];NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];self.endDate = [gregorian dateFromComponents:components];[gregorian release];[components release];

 

2. 计算剩余的天数,小时数,分钟数和秒数。 timeIntervalSinceNow 方法返回设定的时间到现在所间隔的秒数。

NSTimeInterval interval = [self.endDate timeIntervalSinceNow];NSInteger seconds = (int) interval;NSInteger days = seconds / 86400;NSInteger hours = seconds % 86400; NSInteger minutes = hours % 3600;seconds = minutes % 60;hours = hours / 3600;minutes = minutes / 60;labelDay.text = [NSString stringWithFormat:@"%02d", days];labelHours.text = [NSString stringWithFormat:@"%02d", hours];labelMinutes.text = [NSString stringWithFormat:@"%02d", minutes];labelSeconds.text = [NSString stringWithFormat:@"%02d", seconds];NSLog(@"%i | %i | %i | %i", days, hours, minutes, seconds);

 

3. 把[2]中的代码所在的函数(updateCountDown)设置为 NSTimer 的selector。

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

 

全部代码下载地址:

https://github.com/ylem/iPhone-CountDown-Example

 

你可能感兴趣的:(iOS,iphone,components,cocoa,2010,timer,360)