pragma mark ---获取验证码
-(void)getCodeButtonClick:(UIButton *)sender{
[self.view endEditing:YES];
if ([self.phone.text isEqualToString:@""]) {
[self showHint:@"手机号不能为空!"];
return;
}else if (self.phone.text.length != 11){
[self showHint:@"手机号格式不正确"];
return;
}else{
[self startTimeWithButton:sender withTime:5];
}
}
/**
获取验证码,倒计时
@param sender 获取验证码的按钮
@param time 倒计的时间
*/
-(void)startTimeWithButton:(UIButton *)sender withTime:(int)time{
sender.userInteractionEnabled = NO;//关闭交互
sender.backgroundColor = [UIColor whiteColor];
[sender setTitleColor:HRColor(67, 67, 67, 1) forState:UIControlStateNormal];
__block int timeout = time;
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
dispatch_source_set_timer(_timer, dispatch_walltime(NULL, 0), 1.0*NSEC_PER_SEC, 0);//每秒执行
dispatch_source_set_event_handler(_timer, ^{
if (timeout<=0) {//倒计时结束
dispatch_source_cancel(_timer);
dispatch_async(dispatch_get_main_queue(), ^{
//倒计时结束时调用
[sender setTitle:@"重新获取验证码" forState:UIControlStateNormal];
sender.userInteractionEnabled = YES;//打开交互
[sender setTitleColor:[UIColor colorWithHexString:@"e4e4e4" alpha:1] forState:UIControlStateNormal];
});
}else{//倒计时未结束
int seconds = timeout %(time+1);
NSString *strTime = [NSString stringWithFormat:@"%d",seconds];
dispatch_async(dispatch_get_main_queue(), ^{
[sender setTitle:[NSString stringWithFormat:@"%@秒",strTime] forState:UIControlStateNormal];
});
timeout--;
}
});
dispatch_resume(_timer);
}