方法一:使用NSTimer来实现(比较适用于发送短信验证码倒计时)主要是利用NSTimer的scheduledTimerWithTimeInterval方法来每秒执行一次changeTime方法//创建一个Timer,每秒执行一次changeTime:方法NSTimer * ti ...
方法一:使用NSTimer来实现(比较适用于发送短信验证码倒计时)
主要是利用NSTimer的scheduledTimerWithTimeInterval方法来每秒执行一次changeTime方法
//创建一个Timer,每秒执行一次changeTime:方法
NSTimer * timer =[NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(changeTime:) userInfo:nil repeats:YES];
//changeTime
-(void)changeTime:(NSTimer*)timer
{
//点击获取验证码的btn
UIButton * button = (UIButton*)[self.view viewWithTag:99];
if (count == 0) {
//完成后invalidate掉
[timer invalidate];
//59s倒计时
count = 59;
[button setTitle:@"重新获取" forState:UIControlStateNormal];
button.userInteractionEnabled = YES;
button.alpha = 1;
}
else{
[button setTitle:[NSString stringWithFormat:@"%d s",count] forState:UIControlStateNormal];
count--;
}
}
方法二:使用 GCD 来实现(比较使用于商家做某种活动的倒计时)
.h文件中定义一个Timer来控制时间
//倒计时Timer
dispatch_source_t _timer;
.m文件中实现:
//创建一个时间戳
NSDateFormatter *dateFormatter=[[NSDateFormatter alloc] init];
//时间戳的格式
[dateFormatter setDateFormat:@"yyyy/MM/dd HH:mm:ss"];
//将相同时间戳格式的NSString类型的数据转换成NSDate类型的数据
NSDate *endDate = [dateFormatter dateFromString:_EndTime];
NSDate *startDate = [dateFormatter dateFromString:_StartTime];
NSDate *currentDate = [dateFormatter dateFromString:_CurrentTime];
//计算服务器当前时间距离活动结束的时间戳
NSTimeInterval timeInterval =[endDate timeIntervalSinceDate:currentDate];
//计算服务器当前时间与活动开始时间的时间戳
NSTimeInterval StartToNow = [currentDate timeIntervalSinceDate:startDate];
//倒计时时间
__block int timeout = timeInterval;
__block int StartTimeout = StartToNow;
if (timeout!=0) {
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
// 并行队列
// 并行队列可以同时处理多个任务,在不得以的情况下可以用dispatch_queue_create创建,但一般我们都要用系统预定义的并行队列,即全局队列(Global // Concurrent Dispatch Queues)。目前系统预定义了四个不同运行优先级的全局队列,我们可以通过dispatch_get_global_queue来获取它们。
//dispatch_get_global_queue第一个参数是队列的优先级,分别对应四个全局队列:
//DISPATCH_QUEUE_PRIORITY_HIGH
//DISPATCH_QUEUE_PRIORITY_DEFAULT
//DISPATCH_QUEUE_PRIORITY_LOW
//DISPATCH_QUEUE_PRIORITY_BACKGROUND
原标题:iOS中倒计时
关键词:IOS
*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们:
admin#shaoqun.com
(#换成@)。