现在的App都用手机验证码登录了,各种使用按钮做60s倒计时,我这里正好有一个之前用过的,来搞一搞事情
+(void)countDownWith:(UIButton *)sender telNumber:(NSString *)telNumber smsType:(NSString *)smsType block:(void(^)(NSString *verifyCode))block{
sender.userInteractionEnabled = NO;
// 发送手机号 并发送验证码
//这里写请求
[request callVerifyback:^(SKResponse *response) {
__block int timeout=59; //倒计时时间
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 setBackgroundColor:setRGBColor(255, 204, 1)];
[sender setTitle:@"获取验证码" forState:UIControlStateNormal];
sender.userInteractionEnabled = YES;
});
}else{
int seconds = timeout % 60;
NSString *strTime = [NSString stringWithFormat:@"%.2d", seconds];
dispatch_async(dispatch_get_main_queue(), ^{
// [sender setBackgroundColor:[UIColor lightGrayColor]];
[sender setTitle:[NSString stringWithFormat:@"已发送 %@s",strTime] forState:UIControlStateNormal];
});
timeout--;
}
});
dispatch_resume(_timer);
//[SVProgressHUD showSuccessWithStatus:response.data[@"code"]];
block([response.data objectForKey:@"code"]);
} error:^(NSString *errorMsg) {
sender.userInteractionEnabled = YES;
}];
}
按钮的搞定,那其他的控件也是可以的咯,改一改用起来咯!比如现在我要做一个倒计时的label,而且label上面的文字要有缩放效果,那就这样改
+ (void)countDownWith:(UILabel *)sender block:(void(^)())block{
sender.userInteractionEnabled = NO;
__block int timeout=5; //倒计时时间
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 removeFromSuperview];
});
}else{
int seconds = timeout % 60;
NSString *strTime = [NSString stringWithFormat:@"%d", seconds];
dispatch_async(dispatch_get_main_queue(), ^{
sender.text = strTime;
sender.alpha = 1;
sender.transform = CGAffineTransformIdentity;
[UIView animateWithDuration:0.7 animations:^{
CGAffineTransform newTransform = CGAffineTransformScale(sender.transform, 2, 2);//2,2表示放大的大小
sender.transform = newTransform;
} completion:^(BOOL finished) {
[UIView animateWithDuration:0.3 animations:^{
sender.alpha = 0.3;
} completion:^(BOOL finished) {
}];
}];
});
timeout--;
}
});
dispatch_resume(_timer);
}
就是这么简单!