iOS 專案裡需要動態計算行高的場景多到數不完。可以說,只要後端回傳的同一個欄位文字長度沒有上限,客戶端就必須動態算行高。
典型情況:table view 裡頭像、暱稱通常有長度限制,但「狀態」、「心情」這類使用者自由輸入的內容則完全無法預期。
本文的範例特別考慮了效能問題——行高方法會被頻繁呼叫,這是最容易出效能事故的地方,程式碼中會逐段註解說明。
關鍵設計是遵循 MVC:控制器不需要知道 cell 內部有幾個子視圖、各佔多高,它把資料丟給 cell,cell 算好高度回傳,控制器拿著結果設定行高即可。
#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
NSString *status = self.arrDataSource[indexPath.row];
// 直接呼叫 cell 的類方法,把這一列的內容傳進去,
// 有多高由 cell 自己算好回傳。
// 遵循 MVC:cell 多高,控制器不需要知道。
CGFloat statusHeight = [HUserStatusCell tableView:tableView rowHeightForObject:status];
CGFloat iconHeight = 70; // 頭像區的固定高度
return statusHeight + iconHeight;
}
+ (CGFloat)tableView:(UITableView *)tableView rowHeightForObject:(id)object {
CGFloat statusLabelWidth = 150;
// 字串分類提供的方法。同樣的道理:
// 字串有多高,cell 也不需要知道;參數傳進去,怎麼算由 NSString 自己負責。
CGSize statusLabelSize = [object sizeWithLabelWidth:statusLabelWidth
font:[UIFont systemFontOfSize:17]];
return statusLabelSize.height;
}
#import "NSString+StringSize.h"
@implementation NSString (StringSize)
- (CGSize)sizeWithLabelWidth:(CGFloat)width font:(UIFont *)font {
NSDictionary *dict = @{NSFontAttributeName : font};
CGRect rect = [self boundingRectWithSize:CGSizeMake(width, MAXFLOAT)
options:(NSStringDrawingUsesLineFragmentOrigin)
attributes:dict
context:nil];
// 向上取整,避免出現 0.5 像素造成的截斷
CGFloat sizeWidth = ceilf(CGRectGetWidth(rect));
CGFloat sizeHeight = ceilf(CGRectGetHeight(rect));
return CGSizeMake(sizeWidth, sizeHeight);
}
@end
#import "ViewController.h"
#import "HUserStatusCell.h"
@interface ViewController ()<UITableViewDelegate, UITableViewDataSource>
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, copy) NSArray *arrDataSource;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
[self.view addSubview:self.tableView];
}
#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return self.arrDataSource.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
HUserStatusCell *cell = [HUserStatusCell userStatusCellWithTableView:tableView];
[cell setCellDataWithStatusName:self.arrDataSource[indexPath.row]];
return cell;
}
#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
NSString *status = self.arrDataSource[indexPath.row];
// 這裡多說兩句。一開始我寫動態行高時,是把後端資料放進資料源,
// 然後在控制器中依序算好每個模型的屬性值:先預留頭像高度,
// 再算文字高度,加總後放進行高陣列,最後一次算完 10 筆。
// 問題是耦合太緊、不遵循 MVC,效能也不好——
// 當前螢幕只顯示兩列,卻算完了 10 個行高,明顯浪費。
//
// 改成「要顯示才計算」之後,效能提升,控制器可讀性也變好了。
//
// 若還想再優化:建立一個空的行高陣列,第一次算完就快取起來,
// 之後滑到該列直接取用(見 4.1)。注意陣列初始為空時要判空,否則會崩潰。
CGFloat statusHeight = [HUserStatusCell tableView:tableView rowHeightForObject:status];
CGFloat iconHeight = 70;
return statusHeight + iconHeight;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
[tableView deselectRowAtIndexPath:indexPath animated:YES];
}
#pragma mark - lazy
- (UITableView *)tableView {
if (!_tableView) {
_tableView = [[UITableView alloc] initWithFrame:self.view.frame];
_tableView.delegate = self;
_tableView.dataSource = self;
}
return _tableView;
}
- (NSArray *)arrDataSource {
if (!_arrDataSource) {
_arrDataSource = @[
@"這只是一個菜鳥寫的小程式,希望能夠幫助到您",
@"很多 App 一樣,這裡的自定義 cell 需要五花八門,比如頭像暱稱是不變的",
@"但總有會變的,比如涉及社區時,使用者的狀態、簽名等",
@"這一段刻意寫得長一些,用來驗證多行時行高是否計算正確,同時也能觀察 label 的 numberOfLines 設定是否生效",
@"動態行高的關鍵在於:高度計算與資料綁定必須使用同一組參數(字級、寬度),否則會出現文字被截斷或留下大片空白",
@"另一個常見問題是快取 key 設計不當,導致 cell 復用後高度錯亂",
@"如果 cell 內部有多個可變高度的元件,記得把它們的高度全部加總,別只算其中一個",
@"列高計算屬性化之後,後續要調整間距或內距只需改一處,不必回頭修改控制器",
@"最後提醒:boundingRectWithSize 的回傳值記得取 ceilf,避免次像素誤差造成最後一行顯示不全",
@"以上就是這個 demo 想傳達的重點,程式碼本身很簡單,觀念才是關鍵"
];
}
return _arrDataSource;
}
@end
只暴露三個類方法與一個實例方法,盡量不在標頭檔暴露內部屬性——這同樣是 MVC 分層的體現。
#import <UIKit/UIKit.h> @interface HUserStatusCell : UITableViewCell /** 回傳可複用的 cell @param tableView 目前的 tableView */ + (instancetype)userStatusCellWithTableView:(UITableView *)tableView; /** 設定 cell 的資料 @param status 狀態字串 */ - (void)setCellDataWithStatusName:(NSString *)status; /** 傳入每一列的資料,回傳行高 @param tableView 目前的 tableView @param object cell 要展示的內容 */ + (CGFloat)tableView:(UITableView *)tableView rowHeightForObject:(id)object; @end
#import "HUserStatusCell.h"
#import "NSString+StringSize.h"
@interface HUserStatusCell ()
@property (nonatomic, strong) UIImageView *iconImageView;
@property (nonatomic, strong) UILabel *nickNameLabel;
@property (nonatomic, strong) UILabel *statusLabel;
@end
@implementation HUserStatusCell
#pragma mark - init
+ (instancetype)userStatusCellWithTableView:(UITableView *)tableView {
static NSString *cellIdentifier = @"HUserStatusCell";
HUserStatusCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (!cell) {
cell = [[HUserStatusCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:cellIdentifier];
}
return cell;
}
- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self) {
[self.contentView addSubview:self.iconImageView];
[self.contentView addSubview:self.nickNameLabel];
[self.contentView addSubview:self.statusLabel];
}
return self;
}
#pragma mark - public
- (void)setCellDataWithStatusName:(NSString *)status {
self.statusLabel.text = status;
self.nickNameLabel.text = @"小海原創";
self.iconImageView.image = [UIImage imageNamed:@"zth"];
}
+ (CGFloat)tableView:(UITableView *)tableView rowHeightForObject:(id)object {
CGFloat statusLabelWidth = 150;
CGSize statusLabelSize = [object sizeWithLabelWidth:statusLabelWidth
font:[UIFont systemFontOfSize:17]];
return statusLabelSize.height;
}
#pragma mark - private
- (void)layoutSubviews {
[super layoutSubviews];
self.iconImageView.frame = CGRectMake(10, 10, 40, 40);
self.nickNameLabel.frame = CGRectMake(60, 20, 100, 20);
CGFloat statusLabelWidth = 150; // 限制寬度
// 依實際內容回傳高度
CGSize statusLabelSize = [self.statusLabel.text sizeWithLabelWidth:statusLabelWidth
font:[UIFont systemFontOfSize:15]];
self.statusLabel.frame = CGRectMake(60, 60, self.frame.size.width - 60, statusLabelSize.height);
}
#pragma mark - lazy
- (UIImageView *)iconImageView {
if (!_iconImageView) {
_iconImageView = [[UIImageView alloc] init];
_iconImageView.layer.cornerRadius = 4;
_iconImageView.layer.masksToBounds = YES;
// 這兩行程式在除錯時非常有用,能直接看出各子視圖是否重疊
// _iconImageView.layer.borderWidth = 0.5;
// _iconImageView.layer.borderColor = [UIColor redColor].CGColor;
}
return _iconImageView;
}
- (UILabel *)nickNameLabel {
if (!_nickNameLabel) {
_nickNameLabel = [[UILabel alloc] init];
_nickNameLabel.textColor = [UIColor cyanColor];
}
return _nickNameLabel;
}
- (UILabel *)statusLabel {
if (!_statusLabel) {
_statusLabel = [[UILabel alloc] init];
_statusLabel.textAlignment = NSTextAlignmentLeft;
_statusLabel.numberOfLines = 0; // 多行必須設為 0
}
return _statusLabel;
}
@end
行高方法在每次即將顯示時都會被呼叫。如果已經算過,就沒有必要重算——把結果快取起來即可。
做法是在 heightForRowAtIndexPath 中先查快取陣列,命中就直接回傳,未命中才計算並寫入:
#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
// 用安全取值方法,避免陣列越界直接 crash
NSNumber *cellHeight = [self.heightArray h_safeObjectAtIndex:indexPath.row];
if (cellHeight) {
NSLog(@"命中快取,直接回傳行高");
return [cellHeight floatValue];
}
NSString *status = self.arrDataSource[indexPath.row];
CGFloat statusHeight = [HUserStatusCell tableView:tableView rowHeightForObject:status];
CGFloat iconHeight = 70;
CGFloat total = statusHeight + iconHeight;
[self.heightArray addObject:@(total)];
NSLog(@"第一次計算並寫入快取");
return total;
}
開發中陣列越界實在太常見。加一層防護,從此不必再為 index 提心吊膽:
@implementation NSArray (Safe)
- (id)h_safeObjectAtIndex:(NSUInteger)index {
if (self.count == 0) {
NSLog(@"--- array have no objects ---");
return nil;
}
if (index > MAX(self.count - 1, 0)) {
NSLog(@"--- index:%li out of array range ---", (long)index);
return nil;
}
return [self objectAtIndex:index];
}
@end
注意快取陣列的寫入順序:因為 cell 是逐列顯示的,用 addObject 剛好能對應 index;但如果資料來源會動態插入或刪除,就必須改用「以 index 為 key 的字典」或可變陣列搭配預先填 nil,否則快取會與資料錯位。
整套做法的核心其實只有一句話:讓「高度」成為 cell 的知識,而不是控制器的知識。
這帶來三個好處:控制器不再需要知道 cell 的內部結構,因此 cell 改版時控制器不用跟著改;高度計算邏輯集中在 cell 內部,容易維護;搭配快取之後,滑動效能也有了保障。
反過來說,代價是多了一層「資料 → cell → 高度」的往返呼叫。對於 cell 結構單純的列表,這個成本可以忽略;但當 cell 內部有橫向滾動、巢狀版面或自繪內容時,務必確認高度計算用到的參數(字級、寬度、內距)與實際繪製時完全一致,否則就會出現高度算錯、內容被裁掉的問題。