这篇文章主要介绍了IOS实现验证码倒计时功能,点击获取验证码,进入时间倒计时,感兴趣的小伙伴们可以参考一下
验证码倒计时按钮的应用是非常普遍的,该Blog就和你一起来实现验证码倒计时的效果,定义一个发送验证码的按钮,添加点击事件,具体内容如下
具体代码:
定义一个发送验证码的按钮,添加点击事件
//发送验证码按钮
_sentCodeBtn = [[UIButton alloc] initWithFrame:CGRectMake(kScreenWidth - 27 - 4 - 94, CGRectGetMinY(_registerCodeFD.frame) + 4, 94, 40)];
[_sentCodeBtn setBackgroundColor:colorWithRGBA(0, 191, 191, 0.9)];
[_sentCodeBtn setTitle:@"发送验证码" forState:UIControlStateNormal];
[_sentCodeBtn.titleLabel setFont:[UIFont systemFontOfSize:13.0f]];
//设置圆角
[_sentCodeBtn.layer setCornerRadius:3.0f];
[_sentCodeBtn.layer setShouldRasterize:YES];
[_sentCodeBtn.layer setRasterizationScale:[UIScreen mainScreen].scale];
//发送事件
[_sentCodeBtn addTarget:self action:@selector(sentCodeMethod) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:_sentCodeBtn];
监听事件:
//发送验证码
-(void)sentCodeMethod{
NSLog(@"发送验证码。。");
//计时器发送验证码
[self sentPhoneCodeTimeMethod];
//调用发送验证码接口-》
}
//计时器发送验证码
-(void)sentPhoneCodeTimeMethod{
//倒计时时间 - 60秒
__block NSInteger timeOut = 59;
//执行队列
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
//计时器 -》dispatch_source_set_timer自动生成
dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
dispatch_source_set_timer(timer, DISPATCH_TIME_NOW, 1.0 * NSEC_PER_SEC, 0 * NSEC_PER_SEC);
dispatch_source_set_event_handler(timer, ^{
if (timeOut <= 0) {
dispatch_source_cancel(timer);
//主线程设置按钮样式-》
dispatch_async(dispatch_get_main_queue(), ^{
[_sentCodeBtn setTitle:@"发送验证码" forState:UIControlStateNormal];
[_sentCodeBtn setUserInteractionEnabled:YES];
});
}else{
//开始计时
//剩余秒数 seconds
NSInteger seconds = timeOut % 60;
NSString *strTime = [NSString stringWithFormat:@"%.1ld",seconds];
//主线程设置按钮样式
dispatch_async(dispatch_get_main_queue(), ^{
[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:1.0];
[_sentCodeBtn setTitle:[NSString stringWithFormat:@"%@S后重新发送",strTime] forState:UIControlStateNormal];
[UIView commitAnimations];
//计时器件不允许点击
[_sentCodeBtn setUserInteractionEnabled:NO];
});
timeOut--;
}
});
dispatch_resume(timer);
}
以上就是本文的全部内容,希望对大家的学习有所帮助。
沃梦达教程
本文标题为:IOS实现验证码倒计时功能(二)


基础教程推荐
猜你喜欢
- MVVMLight项目Model View结构及全局视图模型注入器 2023-05-07
- iOS中如何判断当前网络环境是2G/3G/4G/5G/WiFi 2023-06-18
- Flutter进阶之实现动画效果(三) 2022-10-28
- Android实现短信验证码输入框 2023-04-29
- Android Compose自定义TextField实现自定义的输入框 2023-05-13
- iOS开发使用XML解析网络数据 2022-11-12
- iOS开发 全机型适配解决方法 2023-01-14
- IOS获取系统相册中照片的示例代码 2023-01-03
- iOS Crash常规跟踪方法及Bugly集成运用详细介绍 2023-01-18
- Android开发Compose集成高德地图实例 2023-06-15