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
相關文章
相關標籤/搜索