iOS倒计时三步曲

第一步:定义一个开始时间(如果需要改变按钮上的显示以及关闭按钮的功能,可在这里设置)

__block int takeTime = 60;

self.timeButton.enabled = NO;

            [self.timeButton setTitleColor:DTCE_COLOR forState:UIControlStateNormal];

            self.timeButton.layer.borderColor = DTCE_COLOR.CGColor;

            [self.timeButton setTitle:[NSString stringWithFormat:@"%i秒",takeTime] forState:UIControlStateNormal];

第二步:设置按钮标题变为数字倒计时

[self.timeButton setTitle:[NSString stringWithFormat:@"%i秒",takeTime] forState:UIControlStateNormal];

第三步:开始时间倒计时

[NSTimer scheduledTimerWithTimeInterval:1 repeats:YES block:^(NSTimer * _Nonnull timer) { 

               //当倒计时为0时(恢复按钮的显示和功能,销毁计时器。这里记得一定要return下,不然会到-1.)

                if(takeTime ==0) {

                    self.timeButton.enabled=YES;

                    [self.timeButton setTitleColor:MW_GrassGreenColor forState:UIControlStateNormal];

                    self.timeButton.layer.borderColor=MW_GrassGreenColor.CGColor;

                    [self.timeButtonsetTitle:@"获取验证码"forState:UIControlStateNormal];

                    [timerinvalidate];//销毁计时器

                    return;

                }

                takeTime --;

                [self.timeButton setTitle:[NSString stringWithFormat:@"%i秒",takeTime] forState:UIControlStateNormal];

            }];

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 如题。不要怀疑,这是篇实用文。 对于我们这些样子不算丑陋可憎,性格也算是容易相处的人而言,让别人讨厌其实是个技术活...
    瞎掰少女阅读 1,050评论 0 1
  • 改变从“心”开始。我们都有过拖沓,前几个月我在找工作的时候也有过这种经历,明明很喜欢的岗位,但是自己迟迟没有行动,...
    爱梦晶阅读 90评论 0 0