[iOS] 封装倒计时(一句话调用,无内存泄漏)

2017-12-08  本文已影响16人  春暖花已开
/**
 倒计时

 @param timeNum 倒计时时长
 @param endTitle 倒计时结束后的文本
 @param countingTitleColor 倒计时中的title颜色
 @param endTitleColor 倒计时结束后的title颜色
 @param countingBgColor 倒计时中的背景颜色
 @param endBgColor 倒计时结束后的背景颜色
 
 注:最初的文字颜色和文字需要在添加控件的Container里设定
 */
- (void)startCountDownTime:(NSInteger)timeNum endTitle:(NSString *)endTitle countingTitleColor:(NSString *)countingTitleColor endTitleColor:(NSString *)endTitleColor countingBgColor:(NSString *)countingBgColor endBgColor:(NSString *)endBgColor;

#pragma mark - *************** 倒计时

- (void)startCountDownTime:(NSInteger)timeNum endTitle:(NSString *)endTitle countingTitleColor:(NSString *)countingTitleColor endTitleColor:(NSString *)endTitleColor countingBgColor:(NSString *)countingBgColor endBgColor:(NSString *)endBgColor {
    
    //倒计时时间
    __block NSInteger timeOut = timeNum;
    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);
    //每秒执行一次
    dispatch_source_set_timer(_timer, dispatch_walltime(NULL, 0), 1.0 * NSEC_PER_SEC, 0);
    dispatch_source_set_event_handler(_timer, ^{
        
        //倒计时结束,关闭
        if (timeOut <= 0) {
            dispatch_source_cancel(_timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                self.layer.backgroundColor = [UIColor colorWithHex:endBgColor].CGColor;
                [self setTitle:endTitle forState:UIControlStateNormal];
                [self setTitleColor:[UIColor colorWithHex:endTitleColor] forState:UIControlStateNormal];
                self.userInteractionEnabled = YES;
            });
        } else {//倒计时中
            dispatch_async(dispatch_get_main_queue(), ^{
                self.layer.backgroundColor = [UIColor colorWithHex:countingBgColor].CGColor;
                [self setTitle:[NSString stringWithFormat:@"%lds重发", timeOut] forState:UIControlStateNormal];
                [self setTitleColor:[UIColor colorWithHex:countingTitleColor] forState:UIControlStateNormal];
                self.userInteractionEnabled = NO;
            });
            timeOut--;
        }
    });
    dispatch_resume(_timer);
}

调用:

[self.btn startCountDownTime:5 endTitle:@"重新获取" countingTitleColor:@"ff0025" endTitleColor:@"ddb86b" countingBgColor:@"00d6ad" endBgColor:@"333333"];
上一篇 下一篇

猜你喜欢

热点阅读