使用NSTimer计时器实现简单的按钮倒计时功能

本文介绍了如何利用NSTimer在iOS开发中实现一个简单的按钮倒计时功能,常用于用户获取验证码等场景。步骤包括设置页面、定义定时器、倒计时方法以及在按钮点击事件中启动定时器。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

现在我们做实际开发的时候,当用户进行注册,支付,修改密码等操作的时候,经常会遇到通过短信获取验证码,为了防止用户频繁的操作按钮,需要对按钮做(60)或者(90)秒的倒计时设置.要实现这样的功能,我们一般使用NSTimer定时器来做倒计时,下面我们来看具体的实现过程.

首先,设置一个简单的页面



然后设置一个定时器:

//定义变量

int seconds = 60;

NSTimer *timer;


//倒计时方法验证码实现倒计时60秒,60秒后按钮变换开始的样子

-(void)timerGetVerifyCodeMethod:(NSTimer *)theTimer {

    

    if (seconds == 1) {

        [theTimer invalidate];

        seconds = 60;

        [_showBtn setEnabled:YES];

        [_showBtn setBackgroundColor:[UIColor redColor]];

        [_showBtn setTitle:@"获取验证码" forState:UIControlStateNormal];

        [_showBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];

        [_showBtn.layer setBorderWidth:0.5];

        

    }else{

        seconds--;

        NSString *title = [NSString stringWithFormat:@"重新发送(%d)",seconds];

        [_showBtn setTitle:title forState:UIControlStateNormal];

        [_showBtn setEnabled:NO];

        [_showBtn setBackgroundColor:[UIColor grayColor]];

        [_showBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];

    }

    

}


最后,在按钮点击事件中,调用定时器:

- (IBAction)doAlertViewShow:(UIButton *)sender {

//    seconds = 60;

    timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(timerGetVerifyCodeMethod:) userInfo:nil repeats:YES];

    

}


这样就可以完成一个简单的按钮定时器功能了.实现效果如下:



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值