跨平台开发常用的第三方平时收藏

iOS 在cell中使用倒计时的处理方法

2016-09-15  本文已影响4462人  大头herob

注: 这篇文章因无法重新编辑, 已重写, 请参考新的文章: iOS 在cell中使用倒计时的处理方法(新)

需求: 在UITableViewCell中每条数据中显示该内容的倒计时, 并随时间进行倒数

想法: 1.在每个cell中添加NSTimer, 负责对cell的倒数                                                     

出现的问题: cell有重用机制,每次重用时数据不好处理, 而且每个cell的倒数数不同, 需要在重用时对NSTimer进行废除并重新开启, 如果显示的cell数量过多, 需要创建很多的NSTimer对象

2. 在模型中添加NSTimer, 负责对数据进行倒计数                             

 出现的问题: 与想法1一样, 因为cell重用, 以及数据数量导致出现一样的问题

解决方案: 创建倒计时管理类, 拥有一个时间差属性, 并且每秒对时间差进行加1的操作,并发出一个通知;     而每个cell都监听这个通知, 在通知回调中, 将服务器返回的剩余时间减去时间差再进行格式化显示即可.   

好处: 全局只需要一个NSTimer对象, 没有耦合性, 不需要对NSTimer作过多的操作;  

效果如下: 

demo效果图

Demo地址: (已增加swift版本)

GitHub - herobin22/OYCountDownManager: iOS在cell中使用倒计时的处理方法

GitHub - herobin22/OYCountDownManager-Swift: iOS在cell中使用倒计时的处理方法

使用方法: 

1. 导入"OYCountDownManager.h"

2. 在第一次使用的地方调用[kCountDownManager start]核心代码:

- (void)viewDidLoad {

     [super viewDidLoad];

    // 启动倒计时管理 

    [kCountDownManager start];

}

3. 在Cell中监听通知 kCountDownNotification

- (instancetype)initWithFrame:(CGRect)frame

{

     self = [super initWithFrame:frame];

     if (self) {

     // 监听通知

      [[NSNotificationCenter defaultCenter] addObserver:self    selector:@selector(countDownNotification)    name:kCountDownNotification object:nil];

}     

    return self;

}

4. 在cell设置通知回调, 取得时间差, 根据时间差进行处理

/// 计算倒计时

NSInteger countDown = [self.model.count integerValue] - kCountDownManager.timeInterval;

if (countDown < 0) return;

/// 重新赋值

self.timeLabel.text = [NSString stringWithFormat:@"倒计时%02zd:%02zd:%02zd", countDown/3600, (countDown/60)%60, countDown%60];

5. 当刷新数据时,调用[kCountDownManager reload]

- (void)reloadData {

// 网络加载数据

// 调用[kCountDownManager reload]

[kCountDownManager reload];

// 刷新

[self.tableView reloadData];

}

倒计时管理类

CountDownManager.h CountDownManager.m

UITableViewCell 中监听CountDown的通知, 并设置回调

上一篇 下一篇

猜你喜欢

热点阅读