利用GCD实现倒计时功能

// 按钮的模式为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);

}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容