UIButton *button = [UIButton buttonWithType:(UIButtonTypeCustom)];
设置位置
button.frame = CGRectMake(100, 100, 100, 100);
button.tag = 1000;
设置背景颜色
button.backgroundColor = [UIColor cyanColor];
[button addTarget: self action:@selector(buttonClick:) forControlEvents:(UIControlEventTouchUpInside)];
给一个时间的初值
self.number = 5;
@property (nonatomic ,assign)NSInteger number;
两个关键的方法
- (void)buttonClick:(UIButton *)button
{
NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timer:) userInfo:@"button倒计时" repeats:YES];
[timer fire];
button.userInteractionEnabled = NO;
}
- (void)timer:(NSTimer *)timer
{
NSString *title = [NSString stringWithFormat:@"%ld",self.number--];
UIButton *button = (UIButton *)[self.view viewWithTag:1000];
[button setTitle:title forState:(UIControlStateNormal)];
if ([[button titleForState:(UIControlStateNormal)] isEqualToString:@"0"]) {
[timer invalidate];
[button setTitle:@"重新发送验证码" forState:(UIControlStateNormal)];
button.userInteractionEnabled = YES;
self.number = 5;
}
NSLog(@"调用了");
}