iOS——设置验证码倒计时

情景

在日常生活中,我们注册账号时,大多数是通过和手机绑定,会发送一个验证码,从而实现注册,最近写了一个登录注册界面,利用到了这种方法。

实现验证码倒计时

一开始想到了一种非常简单的思路,发送验证码本身就是一个UIButton,这里可以给UIButton上绑定一个计时器,按下Button时启动计时器,再计时器上添加相对应的响应事件,每一秒刷新一下UIButton配置的文字。
下面看一下具体的代码:

首先设置三个属性,按钮,计时器,以及一个常量记录时间。

// 发送验证码

@property (nonatomic, strong) UIButton *sendButton;
// 设置验证码倒计时

@property (nonatomic, strong) NSTimer *countDownTimer; // 计时器
@property (nonatomic, assign) int seconds; // 倒计时总时长
@end

设置Button的点击事件,在第一次点击Button时设置为xx秒重发,然后启动计时器。

- (void)buttonClick:(id)sender {
    [_sendButton setTitle:[NSString stringWithFormat:@"60S后重发"]forState:UIControlStateNormal];
    [_sendButton setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    //设置倒计时总时长
    
    _seconds = 60;
    //开始倒计时
    //启动倒计时后会每秒钟调用一次方法
    
    _countDownTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timePress) userInfo:nil repeats:YES];
    _sendButton.userInteractionEnabled = NO;
}

设置对应的定时器事件

- (void)timePress{
    
    _seconds--;
    //当倒计时到0时,做需要的操作,比如验证码过期不能提交
    if (_seconds > 0) {
        //修改按钮显示时间
        [_sendButton setTitle:[NSString stringWithFormat:@"%dS后重发",_seconds] forState:UIControlStateNormal];
    } else {
        [_countDownTimer invalidate];
        [_sendButton setTitle:@"发送验证码" forState:UIControlStateNormal];
        _sendButton.userInteractionEnabled = YES;
    }
}

最后是效果图:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值