// 创建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;
}
Button控件实现发送验证码倒计时方法
最新推荐文章于 2023-07-05 11:07:41 发布