
倒計時效果圖
倒計時代碼
- (void)viewDidLoad {
[super viewDidLoad];
[self createUI];
//? ? [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(createTime:) userInfo:nil? repeats:YES];
NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(timerFire:) userInfo:nil repeats:YES];
}
- (void)createUI
{
_timeLab = [[UILabel alloc]initWithFrame:CGRectMake(kXFrom5(20), kYFrom5(160), kXFrom5(250), kYFrom5(50))];
_timeLab.backgroundColor = [UIColor blackColor];
[_timeLab setTextColor:[UIColor whiteColor]];
[self.view addSubview:_timeLab];
_todayLab = [[UILabel alloc]initWithFrame:CGRectMake(kXFrom5(10), kYFrom5(90), kXFrom5(300), kYFrom5(50))];
_todayLab.backgroundColor = [UIColor blackColor];
[_todayLab setTextColor:[UIColor whiteColor]];
[self.view addSubview:_todayLab];
_fireDateLab = [[UILabel alloc]initWithFrame:CGRectMake(kXFrom5(10), kYFrom5(30), kXFrom5(300), kYFrom5(50))];
_fireDateLab.backgroundColor = [UIColor blackColor];
[_fireDateLab setTextColor:[UIColor whiteColor]];
[self.view addSubview:_fireDateLab];
}
- (void)timerFire:(NSTimer *)timer
{
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *components = [[NSDateComponents alloc] init];
[components setYear:2016];
[components setMonth:7];
[components setDay:2];
[components setHour:9];
[components setMinute:0];
[components setSecond:0];
NSDate *fireDate = [calendar dateFromComponents:components];//目標(biāo)時間
NSDate *today = [NSDate date];//當(dāng)前時間
unsigned int unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;
NSDateComponents *d = [calendar components:unitFlags fromDate:today toDate:fireDate options:0];//計算時間差
_timeLab.text = [NSString stringWithFormat:@"倒計時 %d天%d小時%d%分%d秒", [d day], [d hour], [d minute], [d second]];//倒計時顯示
_todayLab.text = [NSString stringWithFormat:@"現(xiàn)在 %@", today];//現(xiàn)在時間
_fireDateLab.text = [NSString stringWithFormat:@"設(shè)定時間 %@", fireDate];//設(shè)定過去時間
}