IOS实现验证码倒计时功能(二)

时间:2022-02-12 08:25:43

验证码倒计时按钮的应用是非常普遍的,该blog就和你一起来实现验证码倒计时的效果,定义一个发送验证码的按钮,添加点击事件,具体内容如下

IOS实现验证码倒计时功能(二)

IOS实现验证码倒计时功能(二)

具体代码:

定义一个发送验证码的按钮,添加点击事件

?
1
2
3
4
5
6
7
8
9
10
11
12
//发送验证码按钮
 _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];

监听事件:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
//发送验证码
-(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);
}

以上就是本文的全部内容,希望对大家的学习有所帮助。