// 添加定時器
-(void)addTimer{
self.timer = [NSTimer timerWithTimeInterval:1 target:self selector:@selector(countDown) userInfo:nil repeats:YES];
}
// 倒計時操作
-(void)countDown{
self.count = self.count - 1 ;
NSString *title = [NSString stringWithFormat:@"%ds",self.count];
[self.getBVertifyBtn setTitle:title forState:UIControlStateNormal];
// 此處條件如果設(shè)為== 可能會導(dǎo)致計時為負數(shù)
if (self.count <= 0) {
self.getBVertifyBtn.enabled = YES;
[self.timer setFireDate:[NSDate distantFuture]];
[self.getBVertifyBtn setTitle:@"獲取驗證碼" forState:UIControlStateNormal];
}
}
// 定時器的銷毀
-(void)dealloc{
if ([self.timer isValid]) {
[self.timer invalidate];
}
self.timer = nil ;
}
點擊按鈕獲取驗證碼
// 設(shè)置倒計時起始值
self.count = 60 ;
[[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSDefaultRunLoopMode];
[self.timer setFireDate:[NSDate distantPast]];
self.getBVertifyBtn.enabled = NO ;
// 請求服務(wù)器下發(fā)驗證碼到用戶
// 請求成功 && 下發(fā)驗證碼成功(不做任何操作)
// 請求失敗 或者 獲取驗證碼失敗
[self.timer setFireDate:[NSDate distantFuture]];
self.getBVertifyBtn.enabled = YES ;
[self.getBVertifyBtn setTitle:@"獲取驗證碼" forState:UIControlStateNormal];
注意:如果獲取驗證碼的按鈕是通過sb 或xib 創(chuàng)建的要 設(shè)置按鈕的類型為custem
否則 切換數(shù)字時會有閃爍的效果