UITableView和UICollectionViewDate

Cell倒计时

2023-02-27  本文已影响0人  失忆的程序员

倒计时

工具tool

.h

// 

#import <Foundation/Foundation.h>
#import "CountDown.h"

NS_ASSUME_NONNULL_BEGIN

@interface CountDownTool : NSObject

/**
 *  转换
 *  @brief 转换
 *  @param aTimeString 字符串
 *  @return 返回自己要的字符串
 */
+ (NSString *)getNowTimeWithString:(NSString *)aTimeString;

/**
 * 根据传入的年份和月份获得该月份的天数
 *
 * @param year
 *            年份-正整数
 * @param month
 *            月份-正整数
 * @return 返回天数
 */
+ (NSInteger)getDayNumberWithYear:(NSInteger)y month:(NSInteger)m;








@end

NS_ASSUME_NONNULL_END

m

//

#import "CountDownTool.h"

@implementation CountDownTool

//+ (void)updateTimeInVisibleTableViewCells:(UITableView *)tableView cell:(UITableViewCell *)tableViewCell
//{
//    NSArray *cellArys = tableView.visibleCells; // 取出屏幕可见ceLl
//    for (tableViewCell *cell in cellArys)
//    {
//        NSIndexPath *indexPath = [tableView indexPathForCell:cell];
//        cell.countDownLabel.text = [self getNowTimeWithString:dataSource[indexPath.row]];
//        if ([cell.countDownLabel.text isEqualToString:@"活动已经结束!"])
//        {
//            cell.countDownLabel.textColor = [UIColor redColor];
//        }
//        else
//        {
//            cell.countDownLabel.textColor = [UIColor orangeColor];
//        }
//    }
//}

/**
 *  转换
 *  @brief 转换
 *  @param aTimeString 字符串
 *  @return 返回自己要的字符串
 */
+ (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 (hours <= 0 && minutes <= 0 && seconds <= 0)
    {
        return @"活动已经结束!";
    }
    if (days)
    {
        return [NSString stringWithFormat:@"%@天 %@小时 %@分 %@秒", dayStr, hoursStr, minutesStr, secondsStr];
    }
    return [NSString stringWithFormat:@"%@小时 %@分 %@秒", hoursStr, minutesStr, secondsStr];
}

/**
 * 根据传入的年份和月份获得该月份的天数
 *
 * @param year
 *            年份-正整数
 * @param month
 *            月份-正整数
 * @return 返回天数
 */
+ (NSInteger)getDayNumberWithYear:(NSInteger)y month:(NSInteger)m
{
    int days[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
    if (2 == m && 0 == (y % 4) && (0 != (y % 100) || 0 == (y % 400))) {
        days[1] = 29;
    }
    return (days[m - 1]);
}




@end

核心

.h

//

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

@interface CountDown : NSObject

/**
 *  用NSDate日期倒计时
 *  @brief 用NSDate日期倒计时
 *  @param startDate NSDate ,finishDate NSDate
 *  @return void 返回 completeBlock , day hour minute second
 */
- (void)countDownWithStratDate:(NSDate *)startDate finishDate:(NSDate *)finishDate completeBlock:(void (^)(NSInteger day, NSInteger hour, NSInteger minute, NSInteger second))completeBlock;
/**
 *  用时间戳倒计时
 *  @brief 用时间戳倒计时
 *  @param starTimeStamp,finishTimeStamp
 *  @return void 返回
 */
- (void)countDownWithStratTimeStamp:(long long)starTimeStamp finishTimeStamp:(long long)finishTimeStamp completeBlock:(void (^)(NSInteger day, NSInteger hour, NSInteger minute, NSInteger second))completeBlock;
/**
 *  每秒走一次,回调block
 *  @brief 每秒走一次,回调block
 *  @param <#dic 这是个字典#>
 *  @return <#void 这是个空值#>
 */
- (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));
}






@end

VC 中 使用操作

创建视图 并初始化

//
    self.countDown = [[CountDown alloc] init];
    __weak __typeof(self) weakSelf= self;
    ///每秒回调一次
    [self.countDown countDownWithPER_SECBlock:^{
        //ALog(@"666666666666666");
        [weakSelf updateTimeInVisibleCollectionViewCells];
    }];

数据

// 循环创建几个先,
        model.timeSsss = [NSString stringWithFormat:@"2023-04-0%d 14:2%d:0%d", i+2, i+1, i+3];
        model.timeDown = [CountDownTool getNowTimeWithString:model.timeSsss];

每秒都要处理


// MARK: ----- 更新可视区域的cell倒计时
/// 更新可视区域的cell倒计时
- (void)updateTimeInVisibleCollectionViewCells
{
    NSArray *cellArys = self.collectionView.visibleCells; // 取出屏幕可见ceLl
    for (UICollectionViewCell *cell in cellArys)
    {
        if ([cell isKindOfClass:[BaseCollectionTimeCell class]])
        {
            NSIndexPath *indexPath = [self.collectionView indexPathForCell:cell];
            BaseModel *model = self.dataAry[indexPath.section][indexPath.row];
            model.timeDown = [CountDownTool getNowTimeWithString:model.timeSsss];
            [self.collectionView reloadItemsAtIndexPaths:[NSArray arrayWithObjects:[NSIndexPath indexPathForRow:indexPath.row inSection:indexPath.section], nil]];
        }
    }
}



参考区域

参考1

二哈吃青草.gif
上一篇下一篇

猜你喜欢

热点阅读