您的位置:首页 > 其它

使用GCD实现发送短信验证码效果

2016-05-16 13:50 447 查看
- (IBAction)buttonActon:(UIButton *)sender
{
sender.userInteractionEnabled = NO;

// 等待的秒数
__block int count = 5;
// 获取全局队列
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
// 实例化计时器
_timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
// 设置计时器
dispatch_source_set_timer(_timer, dispatch_walltime(NULL, 0), 1 * NSEC_PER_SEC, 0 * NSEC_PER_SEC);
// 设置计时器事件处理
dispatch_source_set_event_handler(_timer, ^{
if (count == 0) {
// 取消计时器
dispatch_source_cancel(_timer);
// 在主队列里处理
dispatch_async(dispatch_get_main_queue(), ^{

// 将按钮置为正常状态
sender.userInteractionEnabled = YES;
sender.titleLabel.font = [UIFont systemFontOfSize:15];
sender.backgroundColor = [UIColor orangeColor];
[sender setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
[sender setTitle:@"发送验证码" forState:UIControlStateNormal];
});
}
else
{
NSString *str = [NSString stringWithFormat:@"剩余(%d)s",count];
// 在主队列里处理
dispatch_async(dispatch_get_main_queue(), ^{
// 按钮显示剩余等待时间
sender.backgroundColor = [UIColor grayColor];
[sender setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
[sender setTitle:str forState:UIControlStateNormal];

});
count--;
}
});
// 开启timer
dispatch_resume(_timer);
}

- (void)dealloc
{
// 取消计时器
if (_timer) dispatch_source_cancel(_timer);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: