标注:Object-C 语言
需要实现的效果
思路: 红色的是一个UIButton 灰色的是一个UILabel ,注意 button 和 label 的坐标要一样 当点击button的时候 label出现 button移除父视图 倒计时结束后,label移除父视图 button出现 如此仿佛循环
具体代码:
#import "ViewController.h"
@interface ViewController ()
{
NSTimer *timer; //定时器
NSInteger leftSconds; //秒数
UIButton *Button;
UILabel *label;
}
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor whiteColor];
leftSconds = 60;
timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(tickDown) userInfo:nil repeats:YES];
timer.fireDate = [NSDate distantFuture];
Button = [UIButton buttonWithType:UIButtonTypeCustom];
Button.frame = CGRectMake(50, 100, 100, 40);
Button.backgroundColor = [UIColor redColor];
[Button setTitle:@"发送验证码" forState:UIControlStateNormal];
[Button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
Button.selected = NO;
[Button addTarget:self action:@selector(action:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:Button];
label = [[UILabel alloc]initWithFrame:CGRectMake(50, 100, 100, 40)];
label.backgroundColor = [UIColor lightGrayColor];
label.adjustsFontSizeToFitWidth = YES;
}
//点击Button 触发的方法
-(void)action:(UIButton *)sender
{
[sender removeFromSuperview];
[self.view addSubview:label];
timer.fireDate = [NSDate distantPast];
}
//定时器 实现的方法
-(void)tickDown{
leftSconds -=1;
if (leftSconds>0) {
label.text = [NSString stringWithFormat:@"%ld秒后重试",leftSconds];
}
if (leftSconds == 0) {
[timer invalidate];
timer.fireDate = [NSDate distantFuture];
[label removeFromSuperview];
[self.view addSubview:Button];
[self viewDidLoad];
}
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end