IOS按钮倒计时

主要功能:按钮实现倒计时进行点击事件(获取验证码、点击事件倒计时...)

以下以获取验证码按钮为例:

 

                   

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均没做后台倒计时处理。

                                                          

                                                    -----辉小鱼

 

转载于:https://www.cnblogs.com/yaocongcong/p/5832398.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值