想做一个计时器,学习了一下日期选择器(UIDatePicker),修改一下应该就可以了,这里先贴出来倒计时器的代码,参考李刚《疯狂IOS讲义》。

此倒计时器的效果如下:

用过设置UIDatePicker的时间作为剩余时间,点击start按钮开始计时,UIdatePicker每隔60s修改一次剩余时间。

代码如下:

@implementation JoyViewController
NSTimer* timer;
NSInteger leftSeconds;

- (void)viewDidLoad
{
 [super viewDidLoad];
 //设置使用Count Down Timer模式
 self.countDonwn.datePickerMode = UIDatePickerModeCountDownTime;
}

-(IBAction)clicked:(id)sender
{
 //获取设置的剩余时间
 leftSeconds = self.countDown.countDuration;
 //禁用UIDatePicker控件
 self.countDown.enabled = NO;
 //禁用开始按钮
 [sender setEnabled] = NO;
 //初始化一个字符串,用来作为警告框的内容
 NSString *message = [[NSString stringWithFormat:@"开始倒计时?您还剩下【%d】秒",leftSeconds];
 //创建一个UIAlertView(警告框)
 UIAlertView* alert = [[UIAlertView alloc]initWithTitle:@"开始倒计时?"
    message:message
    delegate:nil
    cancelButtonTitle:@"确定"
    otherButtonTitles:nil];
 [alert show];
 //启用定时器,每隔60s执行一次tickdown方法
 timer = [NSTimer scheduledTimerWithTimeInterVal:60
  targer:self selector:@selector(tickDown)
  userInfo:nil repeates:YES];
}

- (void) tickDown
{
 //将剩余时间减少60s
 leftSeconds -= 60;
 //修改UIDatePicker的剩余时间
 self.countDown.countDownDuration = leftSeconds;
 if(leftSeconds <= 0)//如果时间小于或者等于0,取消定时器
 {
  [timer invalidate];
  //启用定时器和按钮
  self.countDown.enabled = YES;
  self.startBn.enabled = YES;
 }
}
@end