看过GCD实现验证码倒计时,下面我们来看下NSTimer验证码倒计时
核心代码如下:
- (IBAction)verifyBtn:(UIButton *)sender {
UIButton *button = (UIButton *)sender;
//开始倒计时
countDownTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timeFireMethod) userInfo:nil repeats:YES]; //启动倒计时后会每秒钟调用一次方法 timeFireMethod
self.button = button;
//设置倒计时显示的时间
button.titleLabel.text =[NSString stringWithFormat:@"%d",secondsCountDown];
}
-(void)timeFireMethod{
//倒计时-1
secondsCountDown--;
//修改倒计时标签现实内容
self.button.titleLabel.text=[NSString stringWithFormat:@"%d",secondsCountDown];
if(secondsCountDown == 0){
[countDownTimer invalidate];
[labelText removeFromSuperview];
}
//当倒计时到0时,做需要的操作,比如验证码过期不能提交
if(secondsCountDown==0){
[countDownTimer invalidate];
self.button.titleLabel.text = @"发送验证码";
}
}
可以github下载源代码。查看全部代码。并实现注册界面中的验证码获取倒计时功能
https://github.com/lee727n/Countdown-BY-NSTimer