iOS 手機短信驗證碼等待時間

標註: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

  








發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章