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