具体效果如下
在一个第三方库的基础上进行的修改完善。每次写博客之前,都感觉犹如连绵江水滔滔不绝,一开始写,就各种卡壳,还是直接上代码吧。
三方库.h
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
@interface CountDown : NSObject
///用NSDate日期倒计时
-(void)countDownWithStratDate:(NSDate *)startDate finishDate:(NSDate *)finishDate completeBlock:(void (^)(NSInteger day,NSInteger hour,NSInteger minute,NSInteger second))completeBlock;
///用时间戳倒计时
-(void)countDownWithStratTimeStamp:(long long)starTimeStamp finishTimeStamp:(long long)finishTimeStamp completeBlock:(void (^)(NSInteger day,NSInteger hour,NSInteger minute,NSInteger second))completeBlock;
///每秒走一次,回调block
-(void)countDownWithPER_SECBlock:(void (^)())PER_SECBlock;
-(void)destoryTimer;
-(NSDate *)dateWithLongLong:(long long)longlongValue;
@end
.m
#import "CountDown.h"
@interface CountDown ()
@property(nonatomic,retain) dispatch_source_t timer;
@property(nonatomic,retain) NSDateFormatter *dateFormatter;
@end
@implementation CountDown
- (instancetype)init{
self = [super init];
if (self) {
self.dateFormatter=[[NSDateFormatter alloc] init];
[self.dateFormatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"];
NSTimeZone *localTimeZone = [NSTimeZone localTimeZone];
[self.dateFormatter setTimeZone:localTimeZone];
}
return self;
}
-(void)countDownWithStratDate:(NSDate *)startDate finishDate:(NSDate *)finishDate completeBlock:(void (^)(NSInteger day,NSInteger hour,NSInteger minute,NSInteger second))completeBlock{
if (_timer==nil) {
NSTimeInterval timeInterval =[finishDate timeIntervalSinceDate:startDate];
__block int timeout = timeInterval; //倒计时时间
if (timeout!=0) {
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
_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);
_timer = nil;
dispatch_async(dispatch_get_main_queue(), ^{
completeBlock(0,0,0,0);
});
}else{
int days = (int)(timeout/(3600*24));
int hours = (int)((timeout-days*24*3600)/3600);
int minute = (int)(timeout-days*24*3600-hours*3600)/60;
int second = timeout-days*24*3600-hours*3600-minute*60;
dispatch_async(dispatch_get_main_queue(), ^{
completeBlock(days,hours,minute,second);
});
timeout--;
}
});
dispatch_resume(_timer);
}
}
}
-(void)countDownWithPER_SECBlock:(void (^)())PER_SECBlock{
if (_timer==nil) {
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
_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, ^{
dispatch_async(dispatch_get_main_queue(), ^{
PER_SECBlock();
});
});
dispatch_resume(_timer);
}
}
-(NSDate *)dateWithLongLong:(long long)longlongValue{
long long value = longlongValue/1000;
NSNumber *time = [NSNumber numberWithLongLong:value];
//转换成NSTimeInterval,用longLongValue,防止溢出
NSTimeInterval nsTimeInterval = [time longLongValue];
NSDate *date = [[NSDate alloc] initWithTimeIntervalSince1970:nsTimeInterval];
return date;
}
-(void)countDownWithStratTimeStamp:(long long)starTimeStamp finishTimeStamp:(long long)finishTimeStamp completeBlock:(void (^)(NSInteger day,NSInteger hour,NSInteger minute,NSInteger second))completeBlock{
if (_timer==nil) {
NSDate *finishDate = [self dateWithLongLong:finishTimeStamp];
NSDate *startDate = [self dateWithLongLong:starTimeStamp];
NSTimeInterval timeInterval =[finishDate timeIntervalSinceDate:startDate];
__block int timeout = timeInterval; //倒计时时间
if (timeout!=0) {
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
_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);
_timer = nil;
dispatch_async(dispatch_get_main_queue(), ^{
completeBlock(0,0,0,0);
});
}else{
int days = (int)(timeout/(3600*24));
int hours = (int)((timeout-days*24*3600)/3600);
int minute = (int)(timeout-days*24*3600-hours*3600)/60;
int second = timeout-days*24*3600-hours*3600-minute*60;
dispatch_async(dispatch_get_main_queue(), ^{
completeBlock(days,hours,minute,second);
});
timeout--;
}
});
dispatch_resume(_timer);
}
}
}
/**
* 获取当天的年月日的字符串
* @return 格式为年-月-日
*/
-(NSString *)getNowyyyymmdd{
NSDate *now = [NSDate date];
NSDateFormatter *formatDay = [[NSDateFormatter alloc] init];
formatDay.dateFormat = @"yyyy-MM-dd";
NSString *dayStr = [formatDay stringFromDate:now];
return dayStr;
}
/**
* 主动销毁定时器
* @return 格式为年-月-日
*/
-(void)destoryTimer{
if (_timer) {
dispatch_source_cancel(_timer);
_timer = nil;
}
}
-(void)dealloc{
NSLog(@"%s dealloc",object_getClassName(self));
}
需要倒计时的Controller
@interface WKSeeVideoViewController ()
@property (strong, nonatomic) CountDown *countDown;
@end
- (void)viewDidLoad {
[super viewDidLoad];
self.countDown = [[CountDown alloc] init];
}
//倒计时按钮的点击事件
-(void)okButtonClick:(UIButton*)btn{
//获取btn的tag值,根据tag值获取当前btn的数据源。
NSString * index = [NSString stringWithFormat:@"%ld",btn.tag - 600];
WKVideoInfoListModel * model = self.dataArr[index.integerValue];
//判断当前下标数组是否已包含此btn
BOOLisInsert = [self.timerArrcontainsObject:index];
if(isInsert ==NO) {
[self.timerArraddObject:index];
}
//btn处于“去完成”状态时,才允许进行倒计时操作
if ([btn.titleLabel.text isEqualToString:@"去完成"]) {
//每次倒计时之前,当前时间加上120秒。
[dataSource replaceObjectAtIndex:index.integerValue withObject:[self getCurrentTimesAndAfterTime:model.time]];
__weak__typeof(self) weakSelf=self;
///每秒回调一次
[self.countDown countDownWithPER_SECBlock:^{
[weakSelfupdateTimeInVisibleCells];
}];
}
}
#pragma mark - 倒计时相关⏬⏬⏬⏬⏬⏬⏬⏬⏬⏬⏬⏬
-(void)updateTimeInVisibleCells{
NSArray *cells = self.tableView.visibleCells; //取出屏幕可见ceLl
//下标数组包含的btn才可进行倒计时操作
for (NSString * index in self.timerArr) {
for (WKMakesListCell * cell in cells) {
if (cell.tag == index.integerValue) {
[cell.okButton setTitle:[self getNowTimeWithString:dataSource[cell.tag]] forState:0];
}
}
}
}
(NSString *)getNowTimeWithString:(NSString *)aTimeString{
NSDateFormatter* formater = [[NSDateFormatter alloc] init];
[formater setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
// 截止时间date格式
NSDate *expireDate = [formater dateFromString:aTimeString];
NSDate *nowDate = [NSDate date];
// 当前时间字符串格式
NSString *nowDateStr = [formater stringFromDate:nowDate];
// 当前时间date格式
nowDate = [formater dateFromString:nowDateStr];
NSTimeInterval timeInterval =[expireDate timeIntervalSinceDate:nowDate];
int days = (int)(timeInterval/(3600*24));
int hours = (int)((timeInterval-days*24*3600)/3600);
int minutes = (int)(timeInterval-days*24*3600-hours*3600)/60;
int seconds = timeInterval-days*24*3600-hours*3600-minutes*60;
NSString *dayStr;NSString *hoursStr;NSString *minutesStr;NSString *secondsStr;
//天
dayStr = [NSString stringWithFormat:@"%d",days];
//小时
hoursStr = [NSString stringWithFormat:@"%d",hours];
//分钟
if(minutes<10)
minutesStr = [NSString stringWithFormat:@"0%d",minutes];
else
minutesStr = [NSString stringWithFormat:@"%d",minutes];
//秒
if(seconds < 10)
secondsStr = [NSString stringWithFormat:@"0%d", seconds];
else
secondsStr = [NSString stringWithFormat:@"%d",seconds];
if (minutes<=0&&seconds<=0) {
return @"去完成";
}
if (days) {
//在这里也可以添加天、时、分、秒
return [NSString stringWithFormat:@"%@:%@",minutesStr,secondsStr];
}
//在这里也可以添加时、分、秒
return [NSString stringWithFormat:@"%@:%@", minutesStr,secondsStr];
}
//获取当前的时间 加上若干时间后的时间,单位:秒
-(NSString*)getCurrentTimesAndAfterTime:(NSInteger)afterTime{
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
// ----------设置你想要的格式,hh与HH的区别:分别表示12小时制,24小时制
[formatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"];
//现在时间,你可以输出来看下是什么格式
NSDate *datenow = [NSDate date];
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
NSDateComponents *offsetComponents = [[NSDateComponents alloc] init];
[offsetComponents setSecond:afterTime];//加上若干秒
NSDate *resultDate = [gregorian dateByAddingComponents:offsetComponents toDate:datenow options:0];
//----------将nsdate按formatter格式转成nsstring
NSString *currentTimeString = [formatter stringFromDate:resultDate];
NSLog(@"currentTimeString = %@",currentTimeString);
return currentTimeString;
}