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

来源:互联网 发布:informix查看端口 编辑:程序博客网 时间:2024/05/22 03:14

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

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

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

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

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


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

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


Demo地址: 

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

使用方法: 

1. 导入"OYCountDownManager.h"

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

1
2
3
4
5
- (void)viewDidLoad {
     [super viewDidLoad];
    // 启动倒计时管理 
    [kCountDownManager start];
}

3. 在Cell中监听通知 kCountDownNotification

1
2
3
4
5
6
7
8
9
- (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设置通知回调, 取得时间差, 根据时间差进行处理

/// 计算倒计时

1
2
3
4
NSInteger countDown = [self.model.count integerValue] - kCountDownManager.timeInterval;
if (countDown < 0) return;
/// 重新赋值
self.timeLabel.text = [NSString stringWithFormat:@"倒计时zd:zd:zd", countDown/3600, (countDown/60)%60, countDown%60];

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

1
2
3
4
5
6
7
- (void)reloadData {
// 网络加载数据
// 调用[kCountDownManager reload]
[kCountDownManager reload];
// 刷新
[self.tableView reloadData];
}

倒计时管理类

1646270-acacae6be2ddf665.png

CountDownManager.h

1646270-7f323ec36a80b265.png

CountDownManager.m

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

1646270-6f236a4fe7822d43.png






1 0
原创粉丝点击