GCD-倒计时的使用

2016-11-17  本文已影响0人  small_Sea

GCD 倒计时

#import "UILabel+CountDown.h"
#import <objc/runtime.h>

const char timeKey;
const char titleKey;
const char colorKey;

@implementation UILabel (CountDown)

/**
 倒计时

 @param timeLine 倒计时的时间
 @param title    结束后字符串
 @param subTitle 正在倒计时的字符串
 @param mColor   正在倒计时的颜色
 @param color    倒计时结束的颜色
 */
- (void) startWithTime:(NSInteger)timeLine title:(NSString *)title countDownTitle:(NSString *)subTitle mainColor:(UIColor *)mColor countColor:(UIColor *)color{

// 倒计时时间
__block NSInteger timeOut = timeLine;

dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
objc_setAssociatedObject(self, &timeKey, _timer, OBJC_ASSOCIATION_RETAIN);
objc_setAssociatedObject(self, &titleKey, title, OBJC_ASSOCIATION_RETAIN);
objc_setAssociatedObject(self, &colorKey, color, OBJC_ASSOCIATION_RETAIN);

// 每秒执行一次

dispatch_source_set_timer(_timer, dispatch_walltime(NULL, 0), 1.0 * NSEC_PER_SEC, 0);
dispatch_source_set_event_handler(_timer, ^{
   
    if (timeOut <= 0) {
        [self stopTime];
    }else{
        
        int seconds = --timeOut % 60;
        NSString *timeStr = [NSString stringWithFormat:@"%.02d",seconds];
        dispatch_async(dispatch_get_main_queue(), ^{
           
            self.backgroundColor = mColor;
            self.text = [NSString stringWithFormat:@"%@%@",timeStr,subTitle];
            self.userInteractionEnabled = NO;
        });
    }
});
dispatch_resume(_timer);
}

- (void)stopTime{

dispatch_source_t _timer = objc_getAssociatedObject(self, &timeKey);
dispatch_source_cancel(_timer);
dispatch_async(dispatch_get_main_queue(), ^{
    self.backgroundColor = objc_getAssociatedObject(self, &colorKey);
    self.text = objc_getAssociatedObject(self, &titleKey);
    self.userInteractionEnabled = YES;
});
}

使用

- (void)setLabel{

UILabel *countDown = [[UILabel alloc] initWithFrame:CGRectMake(20, 100, 100, 30)];
countDown.font = [UIFont systemFontOfSize:13];
countDown.textAlignment = NSTextAlignmentCenter;
[self.view addSubview:countDown];
self.countDown = countDown;
[self theLabelCountDown];
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(TapDown:)];
[countDown addGestureRecognizer:tap];
}

- (void)TapDown:(UITapGestureRecognizer *)tap{
[self theLabelCountDown];
}

-(void)theLabelCountDown{
[self.countDown startWithTime:60 title:@"重新发送" countDownTitle:@"倒计时" mainColor:[UIColor redColor] countColor:[UIColor yellowColor]];

}
上一篇 下一篇

猜你喜欢

热点阅读