iOS 验证码 小技术之 UIButton NSTimer 计时器

#import "ViewController.h"

@interface ViewController ()

//自定义按钮属性 button  方便下文更改名称title
@property (nonatomic, retain) UIButton * button;

// 自定义属性 time 作为控制验证码间隔时间
@property (nonatomic, assign) NSInteger time;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.


    // 自定义一个UIButton 作为 发送验证码按钮
    self.button = [UIButton buttonWithType:(UIButtonTypeSystem)];
    // 设置button 位置
    self.button.frame = CGRectMake(100, 100, 100, 30);
    // 设置 按钮背景颜色
    self.button.backgroundColor = [UIColor greenColor];
    // 设置 按钮名称
    [self.button setTitle:@"发送验证码" forState:(UIControlStateNormal)];
    // 给按钮添加点击事件
    [self.button addTarget:self action:@selector(actionButton:) forControlEvents:(UIControlEventTouchUpInside)];
    // 将按钮添加到主界面
    [self.view addSubview:self.button];

    // 设置验证码间隔时间 (可根据实际使用需要设置) 单位为秒
    self.time = 5;
}

// 实现按钮点击方法
- (void)actionButton:(UIButton *)button
{
    // 创建定时器  可以进行循环
    // userInfo  可以看做一个参数或者标示符
    NSTimer * timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(myTimer:) userInfo:@"123" repeats:YES];
    // 计时器启动
    [timer fire];
    // 在进行时间倒计时的时候  关闭button交互
    self.button.userInteractionEnabled = NO;
}

// 实现 timer 的时间变化方法
- (void)myTimer:(NSTimer *)timer
{
    // 在按钮上面显示剩余时间
    [self.button setTitle:[NSString stringWithFormat:@"%ld", self.time--] forState:(UIControlStateNormal)];
    // 当时间减到0的时候 将计时器 归零
    if (self.time < 0) {
        // 当时间为0 时改变按钮名称
        [self.button setTitle:@"重新发送" forState:(UIControlStateNormal)];
        // 开启button 点击事件
        self.button.userInteractionEnabled = YES;
        // 计时器失效
        [timer invalidate];
        // 将时间重置为5
        self.time = 5;
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end

运行成果截图展示:
这里写图片描述

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值