Button控件实现发送验证码倒计时方法

来源:互联网 发布:centos 7 官网下载 编辑:程序博客网 时间:2024/05/16 07:09
// 创建button控件UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];    button.frame = CGRectMake(100, 100, 100, 100);    button.backgroundColor = [UIColor purpleColor];    button.tag = 100;    [button setTitle:@"发送验证码" forState:UIControlStateNormal];    [button addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];    [self.view addSubview:button];// 设置倒计时初值(应该设置成属性)    self.number = 5;}// 实现button点击事件// 点击后触发一个计时器方法 - (void)buttonClick:(UIButton *)button{    // 倒计时核心 每隔 一秒钟 时间递减    // 计时器(每隔多少时间 调用一个方法)    // (NSTimeInterval) 代表时间间隔    NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timerAction:) userInfo:@"button倒计时" repeats:YES];    // 计时器开始    [timer fire];    // 计时器方法开始后 button的交互应该关掉 不然点一次button就会创建一个timer    button.userInteractionEnabled = NO;}// 计时器方法的实现- (void)timerAction:(NSTimer *)timer{    // 改button的标题    UIButton *button = (UIButton *)[self.view viewWithTag:100];    NSString *buttonTitle = [NSString stringWithFormat:@"%ld",self.number--];    [button setTitle:buttonTitle forState:UIControlStateNormal];// 判断倒计时是否结束(标题是否为0)    if ([[button titleForState:UIControlStateNormal] isEqualToString:@"0"]) {        // 停止计时器        [timer invalidate];        // 更改标题        [button setTitle:@"发送验证码" forState:UIControlStateNormal];        // 打开交互        button.userInteractionEnabled = YES;        // 重置时间        self.number = 5;    }
0 0
原创粉丝点击