短信验证码倒计时
一般是个按键,设定一个定时器,每秒更新button的title,代码如下
@interface BPBaseViewController ()
@property (nonatomic, strong) NSTimer *codeTime;
@end
- (void)resetSmsVerifyCodeTimer:(UIButton *)button{
[button setTitle:@"60" forState:UIControlStateNormal];
[button setUserInteractionEnabled:NO];
_codeTime = [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(updateTimerText:) userInfo:button repeats:YES];
}
- (void)updateTimerText:(NSTimer *)timer {
UIButton *button = [timer userInfo];
NSString *countdown = button.titleLabel.text;
if([countdown isEqualToString:@"0"] || [countdown intValue] < 1) {
[self cancelSMSTimer:timer];
}
else {
int icountdown = [countdown intValue];
icountdown--;
NSString *ncountdown= [[NSString alloc] initWithFormat:@"%d",icountdown];
[button setTitle:ncountdown forState:UIControlStateNormal];
}
}
- (void)cancelSMSTimer:(NSTimer *)timer{
UIButton *button = [timer userInfo];
if ([_codeTime isValid]) {
[_codeTime invalidate];
_codeTime = nil;
}
[button setTitle:@"获取验证码" forState:UIControlStateNormal];
button.userInteractionEnabled = YES;
}