平日工作比較忙,趁著十一假期閒下來終於有時間寫點東西,這篇記錄一下我對 tableView 的一些思考。
提到 tableView,相信每個 iOS 開發者都不陌生,它是我們最常用的控制項之一,繼承自 scrollView。它是個相當神奇的控制項:仿佛擁有無窮無盡的子控制項,可以在上面承載成千上萬行的 cell,卻不會讓記憶體暴衝、也不會造成畫面卡頓。但如果它真的創建了上萬個 cell,各種問題立刻就會浮現。它究竟是如何做到「裝載海量子控制項卻依然流暢」的?
大家都知道答案在於重用機制,但它是如何實現的?多數人理解得並不夠透徹。接下來我會帶大家一起實作一個簡易版的 tableView,重點放在重用機制的落地,讀完之後你對 tableView 應該會有更深一層的認識。
cell 重用本質上使用的是享元模式。下面我們一步步把它做出來。
首先,tableView 必然繼承自 UIScrollView。在 UIScrollView 滑動時,我們需要不斷檢查:是否有新的 cell 進入了可見範圍需要顯示,是否有舊的 cell 離開了範圍需要移除。這一步可以透過重寫
layoutSubviews或setContentOffset來實現。在該方法中,先計算出當前需要顯示第幾行到第幾行,把這些 cell 放上螢幕,最後移除離開螢幕的 cell。
第一步:計算需要顯示第幾行到第幾行
用一個全域陣列存放一個個描述 cell 資訊的物件,每個物件包含起始位置、高度以及所屬的 indexPath。我們可以透過遍歷或二分查找快速定位當前可見範圍的起始行與結束行。二分查找的時間複雜度為 O(log n),一萬次資料最多也只需約 14 次比較,因此這裡採用二分查找。Foundation 框架已經封裝好二分查找,直接沿用即可,當然也可以自己實作。
// 計算將要顯示的是第幾行到第幾行
- (NSRange)numberOfRowsWillShowInPGLTableView:(CGFloat)start end:(CGFloat)end {
PGLRowDetail *startDetail = [[PGLRowDetail alloc] init];
startDetail.startY = start;
PGLRowDetail *endDetail = [[PGLRowDetail alloc] init];
endDetail.startY = end;
NSInteger startIndex = [self.rowRecords indexOfObject:startDetail
inSortedRange:NSMakeRange(0, self.rowRecords.count)
options:NSBinarySearchingInsertionIndex
usingComparator:^NSComparisonResult(PGLRowDetail *obj1, PGLRowDetail *obj2) {
if (obj1.startY < obj2.startY) return NSOrderedAscending;
return NSOrderedDescending;
}];
if (startIndex > 0) startIndex--;
NSInteger endIndex = [self.rowRecords indexOfObject:endDetail
inSortedRange:NSMakeRange(0, self.rowRecords.count - 1)
options:NSBinarySearchingInsertionIndex
usingComparator:^NSComparisonResult(PGLRowDetail *obj1, PGLRowDetail *obj2) {
if (obj1.startY < obj2.startY) return NSOrderedAscending;
return NSOrderedDescending;
}];
if (endIndex > 0) endIndex--;
return NSMakeRange(startIndex, endIndex - startIndex + 1);
}
第二步:判斷可見 cell 是否已在畫面上,若無則向 dataSource 索取cellForRow 會先到重用池中依識別碼尋找,找到就從池中移除並複用,找不到才重新創建,然後加到畫面上。
// 放置需要顯示的 cell
for (NSUInteger i = range.location; i < range.location + range.length; i++) {
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:i inSection:0];
PGLTableViewCell *cell = [self.visibleCells objectForKey:@(i)];
if (cell == nil) {
cell = [self.dataSource pgtableView:self cellForRowAtIndexPath:indexPath];
[self.visibleCells setObject:cell forKey:@(i)];
PGLRowDetail *detail = self.rowRecords[i];
cell.frame = CGRectMake(0, detail.startY, self.frame.size.width, detail.rowHeight);
[self addSubview:cell];
}
}
// 從重用池中取得 cell
- (PGLTableViewCell *)dequeueReusableCellWithIdentifier:(NSString *)identifier {
PGLTableViewCell *reuseCell = nil;
for (PGLTableViewCell *cell in self.reusePool) {
if ([cell.reuseIdentifier isEqualToString:identifier]) {
reuseCell = cell;
break;
}
}
if (reuseCell) {
[self.reusePool removeObject:reuseCell];
}
return reuseCell;
}
第三步:判斷 cell 是否已離開螢幕,若已離開則移除並放回重用池
// 移除離開螢幕的 cell,同時放入重用池
NSArray *allVisibleCells = [self.visibleCells allKeys];
for (NSNumber *numb in allVisibleCells) {
if (!NSLocationInRange([numb integerValue], range)) {
PGLTableViewCell *cell = [self.visibleCells objectForKey:numb];
[self.reusePool addObject:cell];
[self.visibleCells removeObjectForKey:numb];
[cell removeFromSuperview];
}
}
以上就是重用機制的完整實作。核心邏輯其實只有三件事:算出可見範圍、把範圍內的 cell 補上、把範圍外的 cell 回收進池子。
總結:當然,真正的 tableView 還有大量強大能力,例如豐富的代理與資料來源方法、cell 高度快取、多 section 支援等,這裡只演示了最關鍵的重用機制。有興趣的話完全可以試著自己補齊其他部分,我相信對你來說應該只是小問題。
文章轉自 PaulLi 哥的簡書
原文連結:https://www.jianshu.com/p/6abec6dec19f
著作權歸作者所有,轉載請聯繫作者獲得授權,並標註「簡書作者」。