iOS如何实现短信验证码倒计时

  介绍

小编给大家分享一下iOS如何实现短信验证码倒计时,相信大部分人都还不怎么了解,因此分享这篇文章给大家参考一下,希望大家阅读完这篇文章后大有收获、下面让我们一起去了解一下吧!

<强>一、利用NSTimer计时器

1。新建一个UIButton按钮,设置成属性,名为codeButton。(UIButton样式一定要为自定义,否则后面倒计时数秒时会出现闪烁现象)

2。定义一个NSTimer的属性,名为计时器,同时定义一个用于计时的int变量时间,设置初始值为60。

//启动一个定时器   时间=self.timer  [NSTimer  scheduledTimerWithTimeInterval: 1,目标:self 选择器:@ selector (operatePerSecond),用户信息:nil 重复:是的);   ,//实现定时器中的方法   安康;(空白)operatePerSecond  {   ,,,if  (==time  1), {   ,,,,,(self.timer 无效);   ,,,,,time =, 60;   ,,,,,(self.codeButton  setTitle: @"重新获取“,forState: UIControlStateNormal);   ,,,,,self.codeButton.tintColor =, [UIColor  blackColor];   ,,,,,self.codeButton.enabled =,是的,   ,,,}else  {   ,,,,,time  -;   ,,,,,(self.codeButton  setTitle: [NSString  stringWithFormat: @" % ds",,时间),forState: UIControlStateNormal);   ,,,}   }

3。此时主要逻辑已经完成,但要记得:在本页面即将消失的时候也要停掉计时器self.timer。

<强>二,利用GCD实现

1。定义一个用于计时的时间(此时要用块修饰)——安康;,块int时间=60;

,,//倒计时时间   __block 才能int  timeout =, 60;   dispatch_queue_t 才能;queue =, dispatch_get_global_queue (DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);   dispatch_source_t 才能;timer =, dispatch_source_create (DISPATCH_SOURCE_TYPE_TIMER, 0, 0,,队列);   dispatch_source_set_timer才能(计时器,DISPATCH_TIME_NOW,, 1.0, *, NSEC_PER_SEC,, 0, *, NSEC_PER_SEC);   dispatch_source_set_event_handler才能(计时器,^ {   ,,,如果(==timeout  1) {   ,,,,,//倒计时结束,关闭   ,,,,,dispatch_source_cancel(计时器);   ,,,,,设置(dispatch_get_main_queue (),, ^ {   ,,,,,timeout =, 60;   ,,,,,(self.codeButton  setTitle: @"重新获取“,forState: UIControlStateNormal);   ,,,,,self.codeButton.tintColor =, [UIColor  blackColor];   ,,,,,self.codeButton.enabled =,是的,   ,,,,,});   还有,,,}{   ,,,,,NSString  * strTime =, (NSString  stringWithFormat: @" % ds",超时);   ,,,,,设置(dispatch_get_main_queue (),, ^ {   ,,,,,,,(self.codeButton  setTitle: strTime  forState: UIControlStateNormal);   ,,,,,});   ,,,,,超时,   ,,,}   ,,});   dispatch_resume(计时器);

2。把上述代码写入点击方法中即可实现倒计时效果。

以上是“iOS如何实现短信验证码倒计时”这篇文章的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注行业资讯频道!

iOS如何实现短信验证码倒计时