倒计时效果图
倒计时代码
- (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];//目标时间
NSDate *today = [NSDate date];//当前时间
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:@"现在 %@", today];//现在时间
_fireDateLab.text = [NSString stringWithFormat:@"设定时间 %@", fireDate];//设定过去时间
}
网友评论