給按鈕加倒計時的代碼
1、聲明屬性
{
NSInteger _timerNo;
NSTimer *_timer;
}
2、在viewDidLoad中設(shè)置按鈕初狀態(tài)
self.Btn.titleLabel.text = @" 獲取驗證碼";
[self.Btn setTitle:@" 獲取驗證碼" forState:UIControlStateDisabled];
[self.Btn setBackgroundColor:[UIColor lightGrayColor] forState:UIControlStateDisabled];
3、在按鈕觸發(fā)方法中觸發(fā)倒計時計時器
if (returnCode != 0) {
[_timer invalidate];
self.Btn.enabled = YES;
NSString *msg = responseObj[@"msg"];
[MBProgressHUD showError:msg];
}else{
[self startSendAuthcode:sender];//若剛開始搭界面,假數(shù)據(jù) 先放這個方法就行
}
4、添加計時器
//發(fā)送驗證碼
-(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];
}
}