#import <UIKit/UIKit.h>
@interface ViewController : UIViewController
@property (assign, nonatomic) NSInteger surplusSecond;
@property (strong, nonatomic) IBOutlet UILabel *lblMessage;
@property (strong, nonatomic) IBOutlet UIButton *btnSendCAPTCHA;
@end
#import “ViewController.h”
@interface ViewController ()
- (void)layoutUI;
- (void)countDown;
@end
@implementation ViewController
#define kSurplusSecond 5
-
(void)viewDidLoad {
[super viewDidLoad];[self layoutUI];
} -
(void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
} -
(void)layoutUI {
_surplusSecond = kSurplusSecond; //剩余秒数;这里指验证码发送完,间隔多少秒才能再次点击「验证」按钮进行发送验证码_btnSendCAPTCHA.tintColor = [UIColor darkGrayColor];
_btnSendCAPTCHA.layer.masksToBounds = YES;
_btnSendCAPTCHA.layer.cornerRadius = 10.0;
_btnSendCAPTCHA.layer.borderColor = [UIColor grayColor].CGColor;
_btnSendCAPTCHA.layer.borderWidth = 1.0;
}
/**
- 倒计时
*/
-
(void)countDown {
//全局并发队列
dispatch_queue_t globalQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
//主队列;属于串行队列
dispatch_queue_t mainQueue = dispatch_get_main_queue();//定时循环执行事件
//dispatch_source_set_timer 方法值得一提的是最后一个参数(leeway),他告诉系统我们需要计时器触发的精准程度。所有的计时器都不会保证100%精准,这个参数用来告诉系统你希望系统保证精准的努力程度。如果你希望一个计时器每5秒触发一次,并且越准越好,那么你传递0为参数。另外,如果是一个周期性任务,比如检查email,那么你会希望每10分钟检查一次,但是不用那么精准。所以你可以传入60,告诉系统60秒的误差是可接受的。他的意义在于降低资源消耗。
dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, globalQueue);
dispatch_source_set_timer(timer, DISPATCH_TIME_NOW, 1.0 * NSEC_PER_SEC, 0.0 * NSEC_PER_SEC);
dispatch_source_set_event_handler(timer, ^{ //计时器事件处理器
NSLog(@“Event Handler”);
if (_surplusSecond <= 0) {
dispatch_source_cancel(timer); //取消定时循环计时器;使得句柄被调用,即事件被执行
dispatch_async(mainQueue, ^{
_btnSendCAPTCHA.enabled = YES;
[_btnSendCAPTCHA setTitle:@“验证” forState:UIControlStateNormal];_lblMessage.text = @"使用 GCD 实现倒计时效果"; _surplusSecond = kSurplusSecond; }); } else { _surplusSecond--; dispatch_async(mainQueue, ^{ NSString *btnInfo = [NSString stringWithFormat:@"%ld秒", (long)(_surplusSecond + 1)]; _btnSendCAPTCHA.enabled = NO; [_btnSendCAPTCHA setTitle:btnInfo forState:UIControlStateDisabled]; }); }
});
dispatch_source_set_cancel_handler(timer, ^{ //计时器取消处理器;调用 dispatch_source_cancel 时执行
NSLog(@“Cancel Handler”);
});
dispatch_resume(timer); //恢复定时循环计时器;Dispatch Source 创建完后默认状态是挂起的,需要主动恢复,否则事件不会被传递,也不会被执行
} -
(IBAction)sendCAPTCHA:(id)sender {
_lblMessage.text = [NSString stringWithFormat:@“验证码发送成功,%d秒后可重新发送”, kSurplusSecond];[self countDown];
}
@end