给按钮加倒计时的代码
1、声明属性
{
NSInteger _timerNo;
NSTimer *_timer;
}
2、在viewDidLoad中设置按钮初状态
self.Btn.titleLabel.text = @" 获取验证码";
[self.Btn setTitle:@" 获取验证码" forState:UIControlStateDisabled];
[self.Btn setBackgroundColor:[UIColor lightGrayColor] forState:UIControlStateDisabled];
3、在按钮触发方法中触发倒计时计时器
if (returnCode != 0) {
[_timer invalidate];
self.Btn.enabled = YES;
NSString *msg = responseObj[@"msg"];
[MBProgressHUD showError:msg];
}else{
[self startSendAuthcode:sender];//若刚开始搭界面,假数据 先放这个方法就行
}
4、添加计时器
//发送验证码
-(void)startSendAuthcode:(UIButton *)btn{ //计时器
_timerNo = 60;
btn.enabled = NO;
_timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(timerAction:) userInfo:nil repeats:YES];
[[NSRunLoop mainRunLoop] addTimer:_timer forMode:NSDefaultRunLoopMode];
}
//定时器
- (void)timerAction:(NSTimer *)timer{
_timerNo--;
self.Btn.titleLabel.text = [NSString stringWithFormat:@"(%zd)重新验证",_timerNo];
[self.Btn setTitle:[NSString stringWithFormat:@"(%zd)重新验证",_timerNo] forState:UIControlStateDisabled];
if (_timerNo == 0) {
[timer invalidate];
self.Btn.enabled = YES;
self.Btn.titleLabel.text = @"(60)重新验证";
[self.Btn setTitle:@"(60)重新验证" forState:UIControlStateDisabled];
}
}