具體效果如下
在一個第三方庫的基礎(chǔ)上進行的修改完善靴姿。每次寫博客之前,都感覺猶如連綿江水滔滔不絕磁滚,一開始寫佛吓,就各種卡殼,還是直接上代碼吧垂攘。
三方庫.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;
///每秒走一次维雇,回調(diào)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); //每秒執(zhí)行
dispatch_source_set_event_handler(_timer, ^{
if(timeout<=0){ //倒計時結(jié)束,關(guān)閉
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); //每秒執(zhí)行
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];
//轉(zhuǎn)換成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); //每秒執(zhí)行
dispatch_source_set_event_handler(_timer, ^{
if(timeout<=0){ //倒計時結(jié)束吱型,關(guān)閉
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);
}
}
}
/**
* 獲取當(dāng)天的年月日的字符串
* @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值,根據(jù)tag值獲取當(dāng)前btn的數(shù)據(jù)源陨仅。
NSString * index = [NSString stringWithFormat:@"%ld",btn.tag - 600];
WKVideoInfoListModel * model = self.dataArr[index.integerValue];
//判斷當(dāng)前下標數(shù)組是否已包含此btn
BOOLisInsert = [self.timerArrcontainsObject:index];
if(isInsert ==NO) {
[self.timerArraddObject:index];
}
//btn處于“去完成”狀態(tài)時津滞,才允許進行倒計時操作
if ([btn.titleLabel.text isEqualToString:@"去完成"]) {
//每次倒計時之前,當(dāng)前時間加上120秒灼伤。
[dataSource replaceObjectAtIndex:index.integerValue withObject:[self getCurrentTimesAndAfterTime:model.time]];
__weak__typeof(self) weakSelf=self;
///每秒回調(diào)一次
[self.countDown countDownWithPER_SECBlock:^{
[weakSelfupdateTimeInVisibleCells];
}];
}
}
#pragma mark - 倒計時相關(guān)????????????
-(void)updateTimeInVisibleCells{
NSArray *cells = self.tableView.visibleCells; //取出屏幕可見ceLl
//下標數(shù)組包含的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];
// 當(dāng)前時間字符串格式
NSString *nowDateStr = [formater stringFromDate:nowDate];
// 當(dāng)前時間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];
}
//獲取當(dāng)前的時間 加上若干時間后的時間,單位:秒
-(NSString*)getCurrentTimesAndAfterTime:(NSInteger)afterTime{
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
// ----------設(shè)置你想要的格式,hh與HH的區(qū)別:分別表示12小時制,24小時制
[formatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"];
//現(xiàn)在時間,你可以輸出來看下是什么格式
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格式轉(zhuǎn)成nsstring
NSString *currentTimeString = [formatter stringFromDate:resultDate];
NSLog(@"currentTimeString = %@",currentTimeString);
return currentTimeString;
}