iOS 在多個(gè)cell上進(jìn)行單獨(dú)倒計(jì)時(shí)的處理方法

具體效果如下


0ED324CE92FA33CD30EF589D30486DDB.gif

在一個(gè)第三方庫(kù)的基礎(chǔ)上進(jìn)行的修改完善。每次寫(xiě)博客之前,都感覺(jué)猶如連綿江水滔滔不絕,一開(kāi)始寫(xiě),就各種卡殼,還是直接上代碼吧。
三方庫(kù).h

#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>

@interface CountDown : NSObject
///用NSDate日期倒計(jì)時(shí)
-(void)countDownWithStratDate:(NSDate *)startDate finishDate:(NSDate *)finishDate completeBlock:(void (^)(NSInteger day,NSInteger hour,NSInteger minute,NSInteger second))completeBlock;
///用時(shí)間戳倒計(jì)時(shí)
-(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; //倒計(jì)時(shí)時(shí)間
        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){ //倒計(jì)時(shí)結(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; //倒計(jì)時(shí)時(shí)間
        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){ //倒計(jì)時(shí)結(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;
}
/**
 *  主動(dòng)銷(xiāo)毀定時(shí)器
 *  @return 格式為年-月-日
 */
-(void)destoryTimer{
    if (_timer) {
        dispatch_source_cancel(_timer);
        _timer = nil;
    }
}

-(void)dealloc{
    NSLog(@"%s dealloc",object_getClassName(self));
}

需要倒計(jì)時(shí)的Controller

@interface WKSeeVideoViewController ()
@property (strong, nonatomic)  CountDown *countDown;
@end
- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.countDown = [[CountDown alloc] init];

}
//倒計(jì)時(shí)按鈕的點(diǎn)擊事件
-(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)前下標(biāo)數(shù)組是否已包含此btn
    BOOLisInsert = [self.timerArrcontainsObject:index];

    if(isInsert ==NO) {
        [self.timerArraddObject:index];
    }
    //btn處于“去完成”狀態(tài)時(shí),才允許進(jìn)行倒計(jì)時(shí)操作
    if ([btn.titleLabel.text isEqualToString:@"去完成"]) {

        //每次倒計(jì)時(shí)之前,當(dāng)前時(shí)間加上120秒。
        [dataSource replaceObjectAtIndex:index.integerValue withObject:[self getCurrentTimesAndAfterTime:model.time]];

        __weak__typeof(self) weakSelf=self;

        ///每秒回調(diào)一次
        [self.countDown countDownWithPER_SECBlock:^{

            [weakSelfupdateTimeInVisibleCells];

        }];
    }
}
#pragma mark - 倒計(jì)時(shí)相關(guān)????????????
-(void)updateTimeInVisibleCells{
    
    NSArray  *cells = self.tableView.visibleCells; //取出屏幕可見(jiàn)ceLl
    
    //下標(biāo)數(shù)組包含的btn才可進(jìn)行倒計(jì)時(shí)操作
    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"];
    // 截止時(shí)間date格式
    NSDate  *expireDate = [formater dateFromString:aTimeString];
    NSDate  *nowDate = [NSDate date];
    // 當(dāng)前時(shí)間字符串格式
    NSString *nowDateStr = [formater stringFromDate:nowDate];
    // 當(dāng)前時(shí)間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];
    //小時(shí)
    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) {
//在這里也可以添加天、時(shí)、分、秒
        return [NSString stringWithFormat:@"%@:%@",minutesStr,secondsStr];
    }
//在這里也可以添加時(shí)、分、秒
    return [NSString stringWithFormat:@"%@:%@", minutesStr,secondsStr];
}
//獲取當(dāng)前的時(shí)間 加上若干時(shí)間后的時(shí)間,單位:秒
-(NSString*)getCurrentTimesAndAfterTime:(NSInteger)afterTime{
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    
    // ----------設(shè)置你想要的格式,hh與HH的區(qū)別:分別表示12小時(shí)制,24小時(shí)制
    
    [formatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"];
    
    //現(xiàn)在時(shí)間,你可以輸出來(lái)看下是什么格式
    
    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)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容