首先在AppDelegate.h里定义几个属性
//时间
@property (assign,nonatomic) NSInteger time;
//显示时间变化的label
@property (strong,nonatomic) UILabel *label;
@property (retain,nonatomic)NSDate *backDate;
然后在AppDelegate.m中
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
self.window = [[UIWindowalloc] initWithFrame:[UIScreenmainScreen].bounds];
self.window.backgroundColor = [UIColorwhiteColor];
[self.windowmakeKeyAndVisible];
//创建一个label用来显示倒计时开始
_label = [[UILabelalloc] initWithFrame:CGRectMake(50,50, 200, 200)];
_label.backgroundColor = [UIColororangeColor];
_label.textAlignment =NSTextAlignmentCenter;
_label.text =@"倒计时开始";
[self.windowaddSubview:_label];
//从100慢慢减少
_time = 100;
//开启定时器
[NSTimerscheduledTimerWithTimeInterval:1target:selfselector:@selector(timerAction:)userInfo:nilrepeats:YES];
return YES;
}
//定时器调用的方法
- (void)timerAction:(NSTimer *)timer{
_label.text = [NSStringstringWithFormat:@"%ld",_time];
if (_time ==0) {
[timer invalidate];
}
_time--;
}
- (void)applicationWillResignActive:(UIApplication *)application {
//取得当前的时间点
_backDate = [[NSDatedate] retain];
}