IOS實現驗證碼倒計時功能(二)_IOS

來源:互聯網
上載者:User

驗證碼倒計時按鈕的應用是非常普遍的,該Blog就和你一起來實現驗證碼倒計時的效果,定義一個發送驗證碼的按鈕,添加點擊事件,具體內容如下

具體代碼:

定義一個發送驗證碼的按鈕,添加點擊事件

 //發送驗證碼按鈕  _sentCodeBtn = [[UIButton alloc] initWithFrame:CGRectMake(kScreenWidth - 27 - 4 - 94, CGRectGetMinY(_registerCodeFD.frame) + 4, 94, 40)];  [_sentCodeBtn setBackgroundColor:colorWithRGBA(0, 191, 191, 0.9)];  [_sentCodeBtn setTitle:@"發送驗證碼" forState:UIControlStateNormal];  [_sentCodeBtn.titleLabel setFont:[UIFont systemFontOfSize:13.0f]];  //設定圓角  [_sentCodeBtn.layer setCornerRadius:3.0f];  [_sentCodeBtn.layer setShouldRasterize:YES];  [_sentCodeBtn.layer setRasterizationScale:[UIScreen mainScreen].scale];  //發送事件  [_sentCodeBtn addTarget:self action:@selector(sentCodeMethod) forControlEvents:UIControlEventTouchUpInside];  [self.view addSubview:_sentCodeBtn];

監聽事件:

//發送驗證碼-(void)sentCodeMethod{ NSLog(@"發送驗證碼。。"); //計時器發送驗證碼 [self sentPhoneCodeTimeMethod]; //調用發送驗證碼介面-》}//計時器發送驗證碼-(void)sentPhoneCodeTimeMethod{ //倒計時時間 - 60秒 __block NSInteger timeOut = 59; //執行隊列 dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); //計時器 -》dispatch_source_set_timer自動產生 dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue); dispatch_source_set_timer(timer, DISPATCH_TIME_NOW, 1.0 * NSEC_PER_SEC, 0 * NSEC_PER_SEC); dispatch_source_set_event_handler(timer, ^{  if (timeOut <= 0) {   dispatch_source_cancel(timer);   //主線程設定按鈕樣式-》   dispatch_async(dispatch_get_main_queue(), ^{    [_sentCodeBtn setTitle:@"發送驗證碼" forState:UIControlStateNormal];    [_sentCodeBtn setUserInteractionEnabled:YES];   });  }else{   //開始計時   //剩餘秒數 seconds   NSInteger seconds = timeOut % 60;   NSString *strTime = [NSString stringWithFormat:@"%.1ld",seconds];   //主線程設定按鈕樣式   dispatch_async(dispatch_get_main_queue(), ^{    [UIView beginAnimations:nil context:nil];    [UIView setAnimationDuration:1.0];    [_sentCodeBtn setTitle:[NSString stringWithFormat:@"%@S後重新發送",strTime] forState:UIControlStateNormal];    [UIView commitAnimations];    //計時器件不允許點擊    [_sentCodeBtn setUserInteractionEnabled:NO];   });   timeOut--;  } }); dispatch_resume(timer);}

以上就是本文的全部內容,希望對大家的學習有所協助。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.