#pragma mark - Countdown algorithm
- (void)setUpTimer {
self.timeLeft = 15;
//设置resend按钮为隐藏,倒计时label为显示,这种倒计时最好是不要用button做显示,不好看,效果也不明显,具体我给忘了。因为本来是想直接就用button的,就是title显示不同,结果证明不行
[self.resendVerifyCodeButton setHidden:YES];
[self.sendEmailCountTimeLabel setHidden:NO];
[self.sendEmailCountTimeLabel setAlpha:0.5f];//保证半失焦的状态,灰暗
[self reloadCountdownLabel];
[self.countdownTimer invalidate];
self.countdownTimer = nil;
self.countdownTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(countDown:) userInfo:nil repeats:YES];
}
- (void)reloadCountdownLabel {
//倒计时过程中显示的文本
if (self.timeLeft >= 0) {
[self.sendEmailCountTimeLabel setText:[NSString stringWithFormat:@"Resend verification email\n (After %i seconds)",self.timeLeft]];
}
else {
[self.sendEmailCountTimeLabel setText:[NSString stringWithFormat:@"Resend verification email\n (After %i seconds)",0]];
}
}
- (void)countDown:(NSTimer *)timer {
self.timeLeft--;
[self reloadCountdownLabel];
if (self.timeLeft == -1) {
[self.countdownTimer invalidate];
self.countdownTimer = nil;
//倒计时结束的UI:
[self.resendVerifyCodeButton setHidden:NO];
[self.sendEmailCountTimeLabel setHidden:YES];
}
}
使用方式比较简单啦:
点击完resend button,call SMS api成功之后,就可以开始倒计时了。这里就不多写了
- (IBAction)resendVerifyCodeAction:(id)sender {
[self setUpTimer];
}