主要功能:按钮实现倒计时进行点击事件(获取验证码、点击事件倒计时...)
以下以获取验证码按钮为例:
NSInteger _time; //获取验证码按钮计时
@property (strong,nonatomic) NSTimer *timer;//定义一个计时器
初始化一个_time = 10;
//初始化一个验证码按钮
_verification_Button = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width*0.25, 35)];
_verification_Button.center = CGPointMake(self.view.center.x*1.65, 145);
[_verification_Button setTitle:@"获取验证码" forState:UIControlStateNormal];
_verification_Button.titleLabel.font = [UIFont systemFontOfSize:12.0];
_verification_Button.backgroundColor = [UIColor blueColor];
[_verification_Button addTarget:self action:@selector(get_verification_Btn) forControlEvents:UIControlEventTouchUpInside];
_verification_Button.enabled = YES;
[self.view addSubview:_verification_Button];
//获取验证码点击事件
-(void)get_verification_Btn{
[_verification_Button setShowsTouchWhenHighlighted:YES];
_verification_Button.enabled = NO;
[_verification_Button setTitle:[NSString stringWithFormat:@"获取验证码(%zi)",_time] forState:UIControlStateNormal];
_verification_Button.backgroundColor = [UIColor grayColor];
_timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(TimeDown) userInfo:nil repeats:YES];
}
//倒计时
-(void)TimeDown{
_time--;
if (_time == 0) {
[_verification_Button setTitle:@"重新获取" forState:UIControlStateNormal];
_verification_Button.enabled = YES;
_verification_Button.backgroundColor = [UIColor blueColor];
[_timer invalidate];
_timer = nil; //先置空
_time = 10;
return;
}
[_verification_Button setTitle:[NSString stringWithFormat:@"获取验证码(%zi)",_time] forState:UIControlStateNormal];
}
//上述方法只是解决了按钮实现点击后设定指定时间后再次被点击(按钮上进行倒计时),没有将倒计时写如后台或成服务,当按钮进行倒计时时,若离开此页面,则倒计时失效,市场上大部分APP均没做后台倒计时处理。
-----辉小鱼