重新获取验证码的按钮

来源:互联网 发布:西安 长沙 知乎 编辑:程序博客网 时间:2024/05/19 01:13

很多应用在修改密码或者是更改个人信息时,需要用户输入手机验证码,其间有个等待过程,一般为60秒,等待结束后可以重新点击按钮获取新的验证码,在页面来回跳转之后又可以重新计时,简要做以下整理:

在.h文件中声明计时器

@interface LinViewController : UIViewController@property (strong, nonatomic) UIButton * button;@property (strong, nonatomic) NSTimer * timer;@end

在.m中实现,特别是- (void)viewWillAppear:(BOOL)animated 和 - (void)viewWillDisappear:(BOOL)animated 方法

//当页面有跳转的操作的时间需要调用[self.timer invalidate],使计时器停止,否则会造成时间连续走动static int myTime;- (void)viewWillAppear:(BOOL)animated{    [self.timer invalidate];    self.timer= [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(changeButtonName) userInfo:nil repeats:YES];        self.button.enabled = NO;    self.button.titleLabel.text = @"10秒后重新获取";    myTime = 10;}- (void)viewWillDisappear:(BOOL)animated{    [self.timer invalidate];}- (void)changeButtonName{    if (myTime > 0) {        self.button.enabled = NO;        myTime--;        NSString * string = [NSString stringWithFormat:@"%d秒后重新获取",myTime];        NSLog(@"%@===",string);        self.button.titleLabel.text = string;    }else    {        [self.timer invalidate];        self.button.enabled = YES;    }}- (void)addButtonAction{    [self.timer invalidate];    [self viewWillAppear:YES];}- (void)viewDidLoad{    [super viewDidLoad];        self.button = [UIButton buttonWithType:UIButtonTypeRoundedRect];    [self.button setFrame:CGRectMake(90, 90, 200, 30)];    [self.button setTitle:@"重新获取验证码" forState:UIControlStateNormal];    [self.button addTarget:self action:@selector(addButtonAction) forControlEvents:UIControlEventTouchUpInside];    [self.view addSubview:self.button];}


0 0
原创粉丝点击