iOS 在多個cell上進行單獨倒計時的處理方法

具體效果如下


0ED324CE92FA33CD30EF589D30486DDB.gif

在一個第三方庫的基礎(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;
}

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末孔祸,一起剝皮案震驚了整個濱河市隆敢,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌崔慧,老刑警劉巖拂蝎,帶你破解...
    沈念sama閱讀 216,544評論 6 501
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異惶室,居然都是意外死亡温自,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,430評論 3 392
  • 文/潘曉璐 我一進店門皇钞,熙熙樓的掌柜王于貴愁眉苦臉地迎上來悼泌,“玉大人,你說我怎么就攤上這事夹界」堇铮” “怎么了煌茬?”我有些...
    開封第一講書人閱讀 162,764評論 0 353
  • 文/不壞的土叔 我叫張陵倚评,是天一觀的道長。 經(jīng)常有香客問我花墩,道長复斥,這世上最難降的妖魔是什么营密? 我笑而不...
    開封第一講書人閱讀 58,193評論 1 292
  • 正文 為了忘掉前任,我火速辦了婚禮目锭,結(jié)果婚禮上评汰,老公的妹妹穿的比我還像新娘。我一直安慰自己侣集,他們只是感情好键俱,可當(dāng)我...
    茶點故事閱讀 67,216評論 6 388
  • 文/花漫 我一把揭開白布兰绣。 她就那樣靜靜地躺著世分,像睡著了一般。 火紅的嫁衣襯著肌膚如雪缀辩。 梳的紋絲不亂的頭發(fā)上臭埋,一...
    開封第一講書人閱讀 51,182評論 1 299
  • 那天,我揣著相機與錄音臀玄,去河邊找鬼瓢阴。 笑死,一個胖子當(dāng)著我的面吹牛健无,可吹牛的內(nèi)容都是我干的荣恐。 我是一名探鬼主播,決...
    沈念sama閱讀 40,063評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼叠穆!你這毒婦竟也來了少漆?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 38,917評論 0 274
  • 序言:老撾萬榮一對情侶失蹤硼被,失蹤者是張志新(化名)和其女友劉穎示损,沒想到半個月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體嚷硫,經(jīng)...
    沈念sama閱讀 45,329評論 1 310
  • 正文 獨居荒郊野嶺守林人離奇死亡检访,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,543評論 2 332
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了仔掸。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片脆贵。...
    茶點故事閱讀 39,722評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖起暮,靈堂內(nèi)的尸體忽然破棺而出丹禀,到底是詐尸還是另有隱情,我是刑警寧澤鞋怀,帶...
    沈念sama閱讀 35,425評論 5 343
  • 正文 年R本政府宣布双泪,位于F島的核電站,受9級特大地震影響密似,放射性物質(zhì)發(fā)生泄漏焙矛。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 41,019評論 3 326
  • 文/蒙蒙 一残腌、第九天 我趴在偏房一處隱蔽的房頂上張望村斟。 院中可真熱鬧,春花似錦抛猫、人聲如沸蟆盹。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,671評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽逾滥。三九已至,卻和暖如春败匹,著一層夾襖步出監(jiān)牢的瞬間寨昙,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 32,825評論 1 269
  • 我被黑心中介騙來泰國打工掀亩, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留舔哪,地道東北人。 一個月前我還...
    沈念sama閱讀 47,729評論 2 368
  • 正文 我出身青樓槽棍,卻偏偏與公主長得像捉蚤,于是被迫代替她去往敵國和親抬驴。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 44,614評論 2 353