设为首页 加入收藏

TOP

iOS中倒计时(一)
2017-10-13 10:17:20 】 浏览:3510
Tags:iOS 倒计时

方法一:使用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

 

//dispatch_get_global_queue中第二个参数目前系统保留,请设置为0即可。

 

  //每秒执行

            _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);

            dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); 

            dispatch_source_set_event_handler(_timer, ^{

  //倒计时结束,关闭

                if(timeout<=0 || StartTimeout <=0){

                    dispa

首页 上一页 1 2 3 下一页 尾页 1/3/3
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇iOS 学习 - 9.Block 相关 下一篇KVO——下拉改变导航栏透明度

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目