iOSiOS_TipsiOS多线程

利用GCD实现倒计时功能

2015-09-18  本文已影响350人  91阿生

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

}

上一篇下一篇

猜你喜欢

热点阅读