注: 這篇文章因無法重新編輯, 已重寫, 請參考新的文章: iOS 在cell中使用倒計時的處理方法(新)
需求: 在UITableViewCell中每條數(shù)據(jù)中顯示該內(nèi)容的倒計時, 并隨時間進行倒數(shù)
想法: 1.在每個cell中添加NSTimer, 負責(zé)對cell的倒數(shù) ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ??
出現(xiàn)的問題: cell有重用機制,每次重用時數(shù)據(jù)不好處理, 而且每個cell的倒數(shù)數(shù)不同, 需要在重用時對NSTimer進行廢除并重新開啟, 如果顯示的cell數(shù)量過多, 需要創(chuàng)建很多的NSTimer對象
2. 在模型中添加NSTimer, 負責(zé)對數(shù)據(jù)進行倒計數(shù) ? ? ? ? ? ? ? ? ? ? ? ? ? ??
?出現(xiàn)的問題: 與想法1一樣, 因為cell重用, 以及數(shù)據(jù)數(shù)量導(dǎo)致出現(xiàn)一樣的問題
解決方案: 創(chuàng)建倒計時管理類, 擁有一個時間差屬性, 并且每秒對時間差進行加1的操作,并發(fā)出一個通知; ? ? 而每個cell都監(jiān)聽這個通知, 在通知回調(diào)中, 將服務(wù)器返回的剩余時間減去時間差再進行格式化顯示即可. ??
好處: 全局只需要一個NSTimer對象, 沒有耦合性, 不需要對NSTimer作過多的操作; ?
效果如下:?

Demo地址: (已增加swift版本)
GitHub - herobin22/OYCountDownManager: iOS在cell中使用倒計時的處理方法
GitHub - herobin22/OYCountDownManager-Swift: iOS在cell中使用倒計時的處理方法
使用方法:?
1. 導(dǎo)入"OYCountDownManager.h"
2. 在第一次使用的地方調(diào)用[kCountDownManager start]核心代碼:
- (void)viewDidLoad {
? ? ?[super viewDidLoad];
? ? // 啟動倒計時管理?
? ? [kCountDownManager start];
}
3. 在Cell中監(jiān)聽通知 kCountDownNotification
- (instancetype)initWithFrame:(CGRect)frame
{
? ? ?self = [super initWithFrame:frame];
? ? ?if (self) {
? ? ?// 監(jiān)聽通知
? ? ? [[NSNotificationCenter defaultCenter] addObserver:self ? ?selector:@selector(countDownNotification)? ? name:kCountDownNotification object:nil];
} ? ??
? ? return self;
}
4. 在cell設(shè)置通知回調(diào), 取得時間差, 根據(jù)時間差進行處理
/// 計算倒計時
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. 當(dāng)刷新數(shù)據(jù)時,調(diào)用[kCountDownManager reload]
- (void)reloadData {
// 網(wǎng)絡(luò)加載數(shù)據(jù)
// 調(diào)用[kCountDownManager reload]
[kCountDownManager reload];
// 刷新
[self.tableView reloadData];
}
倒計時管理類


UITableViewCell 中監(jiān)聽CountDown的通知, 并設(shè)置回調(diào)
