倒計時定時器控件(GCD)

2017年4月13日
一.效果如下

Paste_Image.png

二.實現

#import <UIKit/UIKit.h>

@interface HuCountTimeView : UIView

@property (nonatomic, strong)UILabel *timeL;

//計時時間到后,回調接口
@property (nonatomic, copy) void (^timeOut)(void);

//到臨界值修改顏色。
@property (nonatomic, copy) blk_t changeColorTimeOut;
/**
 函數初始化函數

 @param timeNum 倒計時最大值,需要轉換成秒
 @param dic 設置倒計時字體顏色等相關參數
 @return 返回倒計時對象
 */
- (id)initWithTime:(NSInteger)timeNum AndDic:(NSDictionary*)dic;
//開始
- (void)startCountDown;
//暫停
- (void)stopCountDown;
//結束
- (void)endCountDown;

//定時器結束
- (void)countDownStop;
//當前耗時
- (NSInteger)getUseTime;
//剩余時間
- (NSInteger)getRemainTime;

@end
#import "HuCountTimeView.h"

@interface HuCountTimeView()
{
    dispatch_source_t _timer;//定時器對象
    NSInteger _timeNum;//初始化倒計時最大值
    NSInteger _originalTimrNum; //出事后就不會變
}

@property (nonatomic, assign)BOOL isCreat;//首次創建Yes
@property (nonatomic, assign)BOOL isStart;//啟動
@property (nonatomic, assign)BOOL isPause;//停止

@property (nonatomic, assign)BOOL needChangeColor;//是否需要改變
@property (nonatomic, assign)BOOL isSecondFlag;//是否只顯示秒數
@property (nonatomic, assign)BOOL isDayFlag;//是否顯示天數

@end


@implementation HuCountTimeView

- (id)initWithTime:(NSInteger)timeNum AndDic:(NSDictionary*)dic
{
    self = [super init];
    if (self) {
        [self initDataWithTime:timeNum];
        [self initViewWithDic:dic];
    }
    
    return self;
}

- (void)initDataWithTime:(NSInteger)timeNum
{
    _originalTimrNum = _timeNum = timeNum;
}

- (void)initViewWithDic:(NSDictionary*)dic
{
    self.timeL = [[UILabel alloc] initWithFrame:CGRectZero];
    _timeL.font =  dic[fontSizeKey] ?: fontsize_T3;
    _timeL.textColor = dic[fontColorKey] ?: [UIColor blackColor];
    _isSecondFlag = dic[isSecond];
    _isDayFlag = dic[@"isDayFlag"];
    [self addSubview:_timeL];
    
    //首次設置frame
    if (_isSecondFlag)
        [self setCoutTimeView:[NSString stringWithFormat:@"%ldS",(long)_timeNum]];
    else if(_isDayFlag)
        [self setCoutTimeView:[HuConfigration timeDayStrWithNum:_timeNum]];
    else
        [self setCoutTimeView:[HuConfigration timeStrWithNum:_timeNum]];
}

- (void)setCoutTimeView:(NSString *)timeStr
{
    _timeL.text = timeStr;
    [self layoutView];
}

//開始
- (void)startCountDown
{
    _isStart = YES;
    [self createCountTime];
}

//暫停
- (void)stopCountDown
{
    if (_isCreat) {
        //掛起
        dispatch_suspend(_timer);
        _isPause = YES;
    }
}

//結束
- (void)endCountDown
{
    if (_isCreat) {
        if(_isPause){
            //恢復
            dispatch_resume(_timer);
            
        }else{
            //移出
            dispatch_source_cancel(_timer);
            [self resetData];
        }
        
        
    }
}
- (void)countDownStop{
    //移出
    dispatch_source_cancel(_timer);
    [self resetData];
}
- (void)createCountTime
{
    if (_isCreat == NO) {
        dispatch_queue_t globalQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
        _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, globalQueue);
        _isCreat = YES;
    }
    
    //設置相關參數
    //1.設置時間間隔,每秒執行一次
    dispatch_source_set_timer(_timer, dispatch_walltime(NULL, 0), 1.0*NSEC_PER_SEC, 0);
    //2.設置相關回調
    WS(weakSelf);
    dispatch_source_set_event_handler(_timer, ^{
        
        NSString *strTime = [HuConfigration timeStrWithNum:_timeNum];
        
        if (_isSecondFlag){
            strTime = [NSString stringWithFormat:@"%ldS",(long)_timeNum];
        }
        
        if (_isDayFlag) {
            strTime = [HuConfigration timeDayStrWithNum:_timeNum];
        }
        
        dispatch_async(dispatch_get_main_queue(), ^{
            //在這根據自己的需求去刷新UI
            [weakSelf setCoutTimeView:strTime];
        });
        
        //時間到了回調
        if (_timeNum <= 0) {
            if(_timeOut){
                if(_timeOut){
                    _timeOut(); //時間到了回調
                }
            }
        }else{
            if(_timeNum <= 600)
            {
                if (_needChangeColor) {
                    if (_changeColorTimeOut) {
                        self.changeColorTimeOut();//修改顏色
                        _needChangeColor = NO;
                    }
                }
            }
            
            _timeNum --;
            
        }
    });
    
    //3.啟動timer
    dispatch_resume(_timer);
}

- (void)setChangeColorTimeOut:(blk_t)blk
{
    if (_changeColorTimeOut == nil) {
        _changeColorTimeOut = blk;
        _needChangeColor = YES;
    }
}

- (void)layoutView
{
    UILabel *tmpLabel = self.timeL;
    tmpLabel.textAlignment = NSTextAlignmentRight;
    CGSize size = [tmpLabel.text sizeWithAttributes:@{NSFontAttributeName:tmpLabel.font}];
    if (size.width < 28) {
        size.width = 28;
    }
    CGRect frame = CGRectMake(0, 0, size.width, 25);
    _timeL.frame = frame;
    frame = self.frame;
    frame.size = _timeL.frame.size;
    self.frame = frame;
}

- (void)resetData
{
    _isStart = NO;
    _isCreat = NO;
    _timeNum = 0;
    
    NSString *defaultString = (_isSecondFlag) ? @"" : [HuConfigration timeStrWithNum:_timeNum];
    if (_isDayFlag) {
        defaultString = [HuConfigration timeDayStrWithNum:_timeNum];
    }
    [self setCoutTimeView:defaultString];
}

- (NSInteger)getUseTime
{
    return _originalTimrNum - _timeNum;
}

- (NSInteger)getRemainTime
{
    return _timeNum;
}

@end

如果您發現本文對你有所幫助,如果您認為其他人也可能受益,請把它分享出去。

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容