iPhone NSDate 应用举例:倒计时

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

 

 

原理很简单:

1. 设定结束的时间

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

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

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

 

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

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

  1. // init endDate to 15:00 11/06/2010
    NSDateComponents *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 方法返回设定的时间到现在所间隔的秒数。

  1. NSTimeInterval interval = [self.endDate timeIntervalSinceNow];
  2. NSInteger seconds = (int) interval;NSInteger days     = seconds / 86400;NSInteger hours       = seconds % 86400;
  3. NSInteger minutes    = hours % 3600;
  4. seconds          = minutes % 60;
  5. hours            = hours / 3600;
  6. minutes          = minutes / 60;
  7. labelDay.text        = [NSString stringWithFormat:@"%02d", days];
  8. labelHours.text     = [NSString stringWithFormat:@"%02d", hours];
  9. labelMinutes.text  = [NSString stringWithFormat:@"%02d", minutes];
  10. labelSeconds.text    = [NSString stringWithFormat:@"%02d", seconds];
  11. NSLog(@"%i | %i | %i | %i", days, hours, minutes, seconds);  

 

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

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

 

全部代码下载地址:

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值