1、倒计时一般的三种方法
- NSTimer
[NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(handleTimer) userInfo:nil repeats:YES];
- Thread方式实现
#pragma mark 线程Thread方式实现
- (IBAction)firstBtnAction:(id)sender {
//创建一个后台线程执行计时操作
[self performSelectorInBackground:@selector(timerThread) withObject:nil];
}
- (void)timerThread {
for (int i = TIMECOUNT; i >= 0 ; i--) {
self.count--;
//切换到主线程中更新UI
[self performSelectorOnMainThread:@selector(updateFirstBtn) withObject:nil waitUntilDone:YES];
sleep(1);
}
}
- GCD
/**
* 1、获取或者创建一个队列,一般情况下获取一个全局的队列
* 2、创建一个定时器模式的事件源
* 3、设置定时器的响应间隔
* 4、设置定时器事件源的响应回调,当定时事件发生时,执行此回调
* 5、启动定时器事件
* 6、取消定时器dispatch源,【必须】
*
*/
#pragma mark GCD实现
- (IBAction)thirdBtnAction:(id)sender {
__block NSInteger second = TIMECOUNT;
//(1)
dispatch_queue_t quene = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
//(2)
dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, quene);
//(3)
dispatch_source_set_timer(timer, DISPATCH_TIME_NOW, 1 * NSEC_PER_SEC, 0 * NSEC_PER_SEC);
//(4)
dispatch_source_set_event_handler(timer, ^{
dispatch_async(dispatch_get_main_queue(), ^{
if (second == 0) {
self.thirdBtn.userInteractionEnabled = YES;
[self.thirdBtn setTitle:[NSString stringWithFormat:@"点击获取验证码"] forState:UIControlStateNormal];
second = TIMECOUNT;
//(6)
dispatch_cancel(timer);
} else {
self.thirdBtn.userInteractionEnabled = NO;
[self.thirdBtn setTitle:[NSString stringWithFormat:@"%ld秒后重新获取",second] forState:UIControlStateNormal];
second--;
}
});
});
//(5)
dispatch_resume(timer);
}
2、cell中多个倒计时的情况
用NSTimer,一定有[[NSRunloop mainloop] addTimer:_timer forMode:NSRunloopCommonModes]
这句,这样就避免了滑动tableView的时候倒计时停止的情况。
参考文章:
https://www.jianshu.com/p/af62a56ef7e2
http://www.cocoachina.com/ios/20161011/17722.html
网友评论