今天做了一个“获取短信验证码”倒计时效果的按钮,应用了NSTimer,顺便也看一下UITextField中密码明文与密文的设置。看效果:
定时器实现代码:
@interface TLDForgetPwdViewController ()
{
int timeNumber; //验证码发送倒计时
NSTimer *countTimer; //定时器
}
- (void)viewDidLoad {
[super viewDidLoad];
_pwdText.secureTextEntry = YES; //初始化密码为密文,NO则为明文
[self makeUI];
}
//获取短信验证码
- (IBAction)gainCodeClick {//xib里面的button
[self makeTimer];
}
-(void)makeTimer
{
[countTimer invalidate];
countTimer = nil;
timeNumber = 60;
_gainCodeBtn.userInteractionEnabled = NO;
//设置定时器
countTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(changeGainCodeBtnUI) userInfo:nil repeats:YES];
//将定时器放入线程池
[[NSRunLoop currentRunLoop]addTimer:countTimer forMode:NSDefaultRunLoopMode];
}
//改变button样式
-(void)changeGainCodeBtnUI
{
if (timeNumber > 0) {
timeNumber = timeNumber - 1;
[_gainCodeBtn setBackgroundColor:[TLDFrameworkConfig shareInstance].appStyleColor];
_gainCodeBtn.titleLabel.text = [NSString stringWithFormat:@"重新发送(%d)",timeNumber];//解决ios7之后的闪动问题
[_gainCodeBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
[_gainCodeBtn setTitle:[NSString stringWithFormat:@"重新发送(%d)",timeNumber] forState:UIControlStateNormal];
} else{
timeNumber = 60;
[countTimer invalidate];
countTimer = nil;
_gainCodeBtn.userInteractionEnabled=YES;
[_gainCodeBtn setTitleColor:[TLDFrameworkConfig shareInstance].appStyleColor forState:UIControlStateNormal];
[_gainCodeBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
[_gainCodeBtn setBackgroundColor:[UIColor whiteColor]];
}
}
//一定要记得释放,否则会内存增加导致溢出
-(void)dealloc{
if (countTimer) { //释放定时器
[countTimer invalidate];
countTimer = 0;
}
}