先寫來一個簡單的距離凌晨還有多少時間,後續經過裏面settime能夠設置任意時間程序員
一.ViewController.h中代碼優化
// // ViewController.h // 倒計時 // // Created by 非凡程序員 on 15/6/10. // Copyright (c) 2015年 wzhen. All rights reserved. // #import <UIKit/UIKit.h> @interface ViewController : UIViewController @property (weak, nonatomic) IBOutlet UILabel *nowtime; @property (weak, nonatomic) IBOutlet UITextField *settime; @property (weak, nonatomic) IBOutlet UILabel *cut; @property (weak, nonatomic) IBOutlet UILabel *cuttime; - (IBAction)start:(id)sender; @end
二.ViewController.m中代碼atom
// // ViewController.m // 倒計時 // // Created by 非凡程序員 on 15/6/10. // Copyright (c) 2015年 wzhen. All rights reserved. // #import "ViewController.h" @interface ViewController () @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(start:) userInfo:nil repeats:YES]; // Do any additional setup after loading the view, typically from a nib. } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } - (IBAction)start:(id)sender { NSDate *today=[NSDate date]; NSDateFormatter *format=[NSDateFormatter new]; [format setDateFormat:@"yyyy年MM月dd日 HH時mm分ss秒"]; [_nowtime setText:[format stringFromDate:today]]; // today=[today dateByAddingTimeInterval:(24*60*60)]; // [_cut setText:[format stringFromDate:today]]; // [_cut setText:@"12日00時00分00秒"]; [_cut setText:_settime.text]; [format setDateFormat:@"HH"]; NSString *h=[format stringFromDate:today]; int hh=[h intValue]; [format setDateFormat:@"mm"]; NSString *m=[format stringFromDate:today]; int mm=[m intValue]; [format setDateFormat:@"ss"]; NSString *s=[format stringFromDate:today]; int ss=[s intValue]; int cuthh=24-hh; int cutmm=60-mm; int cutss=60-ss; [_cuttime setText:[NSString stringWithFormat:@"還剩%i時%i分%i秒",cuthh,cutmm,cutss]]; NSLog(@"today->%@,開始h=%@,m=%@,s=%@,----h=%i,m=%i,s=%i結束",today,h,m,s,cuthh,cutmm,cutss); NSLog(@"cut-->%@",_cut.text); } @end
三.後續優化中經過settime設置定時時間,將下面代碼中小時24和分鐘60改爲與settime相關的變量便可code
int cuthh=24-hh; int cutmm=60-mm;