情景
在日常生活中,我们注册账号时,大多数是通过和手机绑定,会发送一个验证码,从而实现注册,最近写了一个登录注册界面,利用到了这种方法。
实现验证码倒计时
一开始想到了一种非常简单的思路,发送验证码本身就是一个UIButton,这里可以给UIButton上绑定一个计时器,按下Button时启动计时器,再计时器上添加相对应的响应事件,每一秒刷新一下UIButton配置的文字。
下面看一下具体的代码:
首先设置三个属性,按钮,计时器,以及一个常量记录时间。
// 发送验证码
@property (nonatomic, strong) UIButton *sendButton;
// 设置验证码倒计时
@property (nonatomic, strong) NSTimer *countDownTimer; // 计时器
@property (nonatomic, assign) int seconds; // 倒计时总时长
@end
设置Button的点击事件,在第一次点击Button时设置为xx秒重发,然后启动计时器。
- (void)buttonClick:(id)sender {
[_sendButton setTitle:[NSString stringWithFormat:@"60S后重发"]forState:UIControlStateNormal];
[_sendButton setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
//设置倒计时总时长
_seconds = 60;
//开始倒计时
//启动倒计时后会每秒钟调用一次方法
_countDownTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timePress) userInfo:nil repeats:YES];
_sendButton.userInteractionEnabled = NO;
}
设置对应的定时器事件
- (void)timePress{
_seconds--;
//当倒计时到0时,做需要的操作,比如验证码过期不能提交
if (_seconds > 0) {
//修改按钮显示时间
[_sendButton setTitle:[NSString stringWithFormat:@"%dS后重发",_seconds] forState:UIControlStateNormal];
} else {
[_countDownTimer invalidate];
[_sendButton setTitle:@"发送验证码" forState:UIControlStateNormal];
_sendButton.userInteractionEnabled = YES;
}
}
最后是效果图: