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];

            }];

你可能感兴趣的:(iOS倒计时三步曲)