美文网首页iOSiOS_TipsiOS多线程
利用GCD实现倒计时功能

利用GCD实现倒计时功能

作者: 91阿生 | 来源:发表于2015-09-18 10:17 被阅读350次

    // 按钮的模式为UIButtonTypeCustom,如果为UIButtonTypeSystem 倒计时的时候会一闪一闪的. 在使用的时候你可以试试看效果

    __block int countdownTime = CountDownTime;  //CountDownTime:为宏,倒计时的时间

    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);

    dispatch_source_t _time = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);

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

    dispatch_source_set_event_handler(_time, ^{

          if (countdownTime <= 0){  

                 dispatch_source_cancel(_time);  // 倒计时结束关闭

                 dispatch_async(dispatch_get_main_queue(), ^{

                       [_getAuthcodeButton setTitle:@"重新获取验证码"          forState:UIControlStateNormal];

                    _getAuthcodeButton.backgroundColor = [UIColor orangeColor];

                   _getAuthcodeButton.userInteractionEnabled = YES;    });

    }else{

              dispatch_async(dispatch_get_main_queue(), ^{

                   [_getAuthcodeButton setTitle:[NSString stringWithFormat:@"%d秒后重新获取",countdownTime] forState:UIControlStateNormal];

                  _getAuthcodeButton.backgroundColor = [UIColor lightGrayColor];

                  _getAuthcodeButton.userInteractionEnabled = NO;

    });

         countdownTime--;

    }

    });

    dispatch_resume(_time);

    }

    相关文章

      网友评论

        本文标题:利用GCD实现倒计时功能

        本文链接:https://www.haomeiwen.com/subject/oapbcttx.html