iOS--倒计时

#import <UIKit/UIKit.h>


@protocol TimeOverDelegate <NSObject>

-(void)timeOverFinish;

@end

@interface TimeTools : UILabel
@property (nonatomic ,strong)id<TimeOverDelegate>delegate;
-(instancetype)initWithFrame:(CGRect)frame andTime:(int)time;
@end
#import "TimeTools.h"

@interface TimeTools()

{
    int secondsCountDown;
    NSTimer *countDownTimer;
    UILabel *labelText;
}

@end

@implementation TimeTools
-(instancetype)initWithFrame:(CGRect)frame andTime:(int)time{
    if (self == [super initWithFrame:frame]) {
        //设置倒计时总时长
        secondsCountDown = time;
        //开始倒计时
        countDownTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timeFireMethod) userInfo:nil repeats:YES]; //启动倒计时后会每秒钟调用一次方法 timeFireMethod
        //设置倒计时显示的时间
        self.text=[NSString stringWithFormat:@"%d",secondsCountDown];
        self.font = [UIFont systemFontOfSize:15];
        self.textColor = [UIColor whiteColor];
        self.textAlignment = NSTextAlignmentCenter;
    }
    return self;
}
-(void)timeFireMethod{
    //倒计时-1
    secondsCountDown--;
    //修改倒计时标签现实内容
    self.text=[NSString stringWithFormat:@"%d",secondsCountDown];
    //当倒计时到0时,做需要的操作,比如验证码过期不能提交
    if(secondsCountDown==0){
        [countDownTimer invalidate];
        self.text=[NSString stringWithFormat:@"重新发送(%d)",secondsCountDown];
        if ([self.delegate respondsToSelector:@selector(timeOverFinish)]) {
            [self.delegate timeOverFinish];
        }
    }
}
@end


你可能感兴趣的:(iOS--倒计时)