
前陣子在微博上看到 VVeboTableViewDemo 這個不錯的開源項目,主題正是如何優化 UITableView。恰好當時手邊也在折騰類似朋友圈的圖文混排功能,對這塊頗有體會,於是決定把自己對 UITableView 優化的理解系統整理一遍。
UITableView 是 iOS 開發裡最重要的控件之一,它的實現原理頗有講究。先從最基礎的認識說起。
核心思想只有一個:Cell 的重用機制。UITableView 只創建一屏(或一屏稍多)的 Cell,其餘全靠複用。Cell 滑出屏幕後會被放進一個集合,相當於重用池;需要顯示某個位置時先去池裡取,取到就直接用,取不到才新建。這樣做的好處很直接:大幅降低內存開銷。
理解複用之後,再看兩個關鍵回調:tableView:cellForRowAtIndexPath: 和 tableView:heightForRowAtIndexPath:。按常理推測,應該是先建 Cell 再設布局,也就是先調前者;但實際順序恰恰相反。UITableView 繼承自 UIScrollView,必須先確定 contentSize 和每個 Cell 的位置,才能把複用來的 Cell 放到正確坐標上。所以真實流程是:先多次調用 heightForRowAtIndexPath: 確定 contentSize 與 Cell 位置,再調用 cellForRowAtIndexPath: 顯示當前屏幕內的 Cell。
舉個具體例子:要顯示 100 個 Cell,當前屏幕可見 5 個。reload 時,UITableView 會先調用 100 次 heightForRowAtIndexPath:,再調用 5 次 cellForRowAtIndexPath:;滾動時,每有一個 Cell 進出屏幕,都會各觸發一次這兩個方法。
結論很清楚了:優化的第一戰場就是這兩個方法。
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
ContacterTableCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ContacterTableCell"];
if (!cell) {
cell = (ContacterTableCell *)[[[NSBundle mainBundle] loadNibNamed:@"ContacterTableCell" owner:self options:nil] lastObject];
}
NSDictionary *dict = self.dataList[indexPath.row];
[cell setContentInfo:dict];
return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
return cell.frame.size.height;
}初看還算巧妙,但 Cell 一複雜就卡到懷疑人生。為什麼卡?因為在 heightForRowAtIndexPath: 裡調用了 cellForRowAtIndexPath:,而賦值、布局全都在後者裡完成。1000 行數據就意味著 1000 多次完整的 Cell 構建與布局,開銷自然爆炸。
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
NSDictionary *dict = self.dataList[indexPath.row];
return [ContacterTableCell cellHeightOfInfo:dict];
}思路是讓兩個方法各司其職:cellForRowAtIndexPath: 只負責賦值,heightForRowAtIndexPath: 只負責算高度,代碼不要重疊,兩邊都要盡可能簡單。跑一下,滾動明顯順暢許多。
再往前一步:拿到數據後就把布局算好,緩存進數據源,heightForRowAtIndexPath: 直接返回結果。
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
NSDictionary *dict = self.dataList[indexPath.row];
CGRect rect = [dict[@"frame"] CGRectValue];
return rect.size.height;
}這招不算終極方案,但應付簡單界面綽綽有餘。面對朋友圈那樣的圖文混排,仍然扛不住,於是我們要走向更深的一層:自定義 Cell 繪制。
往 Cell 上添加系統控件,本質上都要調用底層接口繪制;控件一多,資源開銷急劇上升。既然如此,不如自己畫。
// 異步繪制
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
CGRect rect = [_data[@"frame"] CGRectValue];
UIGraphicsBeginImageContextWithOptions(rect.size, YES, 0);
CGContextRef context = UIGraphicsGetCurrentContext();
// 整個內容的背景
[[UIColor colorWithRed:250/255.0 green:250/255.0 blue:250/255.0 alpha:1] set];
CGContextFillRect(context, rect);
// 轉發內容的背景
if ([_data valueForKey:@"subData"]) {
[[UIColor colorWithRed:243/255.0 green:243/255.0 blue:243/255.0 alpha:1] set];
CGRect subFrame = [_data[@"subData"][@"frame"] CGRectValue];
CGContextFillRect(context, subFrame);
[[UIColor colorWithRed:200/255.0 green:200/255.0 blue:200/255.0 alpha:1] set];
CGContextFillRect(context, CGRectMake(0, subFrame.origin.y, rect.size.width, .5));
}
// 名字
float leftX = SIZE_GAP_LEFT + SIZE_AVATAR + SIZE_GAP_BIG;
float x = leftX;
float y = (SIZE_AVATAR - (SIZE_FONT_NAME + SIZE_FONT_SUBTITLE + 6)) / 2 - 2 + SIZE_GAP_TOP + SIZE_GAP_SMALL - 5;
[_data[@"name"] drawInContext:context withPosition:CGPointMake(x, y)
andFont:FontWithSize(SIZE_FONT_NAME)
andTextColor:[UIColor colorWithRed:106/255.0 green:140/255.0 blue:181/255.0 alpha:1]
andHeight:rect.size.height];
// 時間 + 設備
y += SIZE_FONT_NAME + 5;
float fromX = leftX;
float size = [UIScreen screenWidth] - leftX;
NSString *from = [NSString stringWithFormat:@"%@ %@", _data[@"time"], _data[@"from"]];
[from drawInContext:context withPosition:CGPointMake(fromX, y)
andFont:FontWithSize(SIZE_FONT_SUBTITLE)
andTextColor:[UIColor colorWithRed:178/255.0 green:178/255.0 blue:178/255.0 alpha:1]
andHeight:rect.size.height andWidth:size];
// 繪製結果轉為圖片,回主線程顯示
UIImage *temp = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
dispatch_async(dispatch_get_main_queue(), ^{
if (flag == drawColorFlag) {
postBGView.frame = rect;
postBGView.image = nil;
postBGView.image = temp;
}
});
// 圖文混排的內容交給 CoreText 繪製
[self drawText];
});這裡只貼了部分邏輯,但套路一致:所有元素都按事先算好的布局去畫。異步繪制的收益明顯;如果改成重寫 drawRect,則不必自己開 GCD,因為 drawRect 本身就是異步執行的。圖文混排建議去研究 CoreText,內容較多這裡不展開。
從 UIScrollView 的角度切入,還有最後一個突破口。
// 按需加載:如果目標行與當前行相差超過指定行數,只在目標滾動範圍前後加載若干行
- (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset {
NSIndexPath *ip = [self indexPathForRowAtPoint:CGPointMake(0, targetContentOffset->y)];
NSIndexPath *cip = [[self indexPathsForVisibleRows] firstObject];
NSInteger skipCount = 8;
if (labs(cip.row - ip.row) > skipCount) {
NSArray *temp = [self indexPathsForRowsInRect:CGRectMake(0, targetContentOffset->y, self.width, self.height)];
NSMutableArray *arr = [NSMutableArray arrayWithArray:temp];
if (velocity.y < 0) {
NSIndexPath *indexPath = [temp lastObject];
if (indexPath.row + 3 < self.dataList.count) {
[arr addObject:[NSIndexPath indexPathForRow:indexPath.row - 3 inSection:0]];
[arr addObject:[NSIndexPath indexPathForRow:indexPath.row - 2 inSection:0]];
[arr addObject:[NSIndexPath indexPathForRow:indexPath.row - 1 inSection:0]];
}
}
[needLoadArr addObjectsFromArray:arr];
}
}並在 cellForRowAtIndexPath: 中加上判斷:
if (needLoadArr.count > 0 && [needLoadArr indexOfObject:indexPath] == NSNotFound) {
[cell clear];
return;
}快速滾動時只加載目標範圍內的 Cell,流暢度提升非常明顯。
UITableView 的優化主要從三個方向下手:
除此之外,還有一些大家都耳熟能詳的細節:
大概有人會問:為什麼示例裡全是手寫代碼建 Cell,現在不是流行 Xib 和 Storyboard 嗎?我的答案是:追求極致性能的時候,手寫更可控。拋開 Xib/Storyboard 需要系統額外解碼這層開銷不談,自定義繪制在它們體系下也難以施展。所以面對複雜且要求高效的界面,我還是傾向於手寫。
當然,如果你的項目已經全面使用 Xib/Storyboard 又需要優化,sunnyxx 的方案值得一讀:https://blog.sunnyxx.com/2015/05/17/cell-height-calculation/
本文分析所用源碼來自開源項目 VVeboTableViewDemo:https://github.com/johnil/VVeboTableViewDemo。理解不到位之處,歡迎交流指正。