实现倒计时
添加属性记录倒计时的初值
@property (nonatomic,assign)NSInteger number;
创建一个按钮
UIButton *button = [UIButton buttonWithType:(UIButtonTypeCustom)];
添加Tag值 方便取出
button.tag = 1000;
给按钮添加属性
button.frame = CGRectMake(100, 100, 100, 100);
button.backgroundColor = [UIColor redColor];
[button setTitle:@”发送验证码” forState:(UIControlStateNormal)];
给按钮设置点击方法
[button addTarget:self action:@selector(buttonAction:) forControlEvents:(UIControlEventTouchUpInside)];
添加到视图上
[self.view addSubview:button];
给倒计时时间的初值
self.number = 5;
实现点击方法
-(void)buttonAction:(UIButton *)button
{
/*
倒计时 核心 每隔一秒钟 时间递减
计时器(每隔多少时间 调用一个方法)
scheduledTimerWithTimeInterval:(NSTimeInterval) 代表时间间隔
target:self selector:@selector(timer:)代表每隔多少时间触发的方法
userInfo:@”button倒计时” 代表标题
repeats:YES 代表是否重复
*/
NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timer:) userInfo:@”button倒计时” repeats:YES];
计时器开始
[timer fire];
把交互先关上
button.userInteractionEnabled = NO;
}
实现每个时间间隔中重复触发的方法
-(void)timer:(NSTimer *)timer
{
通过tag值取出按钮视图
UIButton button = (UIButton )[self.view viewWithTag:1000];
改Button的标题
NSString *title = [NSString stringWithFormat:@”%ld”,self.number–];
[button setTitle:title forState:(UIControlStateNormal)];
判断倒计时 是否结束 标题是否为零
if ([[button titleForState:(UIControlStateNormal)]isEqualToString:@”0”]) {
停止计时器
[timer invalidate];
改Button的标题
[button setTitle:@”重新发送验证” forState:(UIControlStateNormal)];
把交互打开
button.userInteractionEnabled = YES;
重置时间
self.number = 5;
}
}