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

2016-12-13  本文已影响0人  devdawei
.h文件中:
@property (nonatomic, strong) dispatch_source_t timer;

.m文件中:
- (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);
}
上一篇下一篇

猜你喜欢

热点阅读