實現 Cell 高度隨內容自適應,核心在於 heightForRowAtIndexPath 與 cellForRowAtIndexPath 返回一致的高度計算邏輯。本文提供基於 UILabel sizeToFit 的經典方案(iOS 7+ 推薦使用 Auto Layout 自動計算)。
@interface ViewController ()
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *dataList; // 存儲不同長度的字符串
@end
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellID = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellID];
if (!cell) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellID];
UILabel *label = [[UILabel alloc] initWithFrame:CGRectZero];
label.tag = 100;
label.numberOfLines = 0;
label.lineBreakMode = NSLineBreakByWordWrapping;
label.font = [UIFont systemFontOfSize:14];
label.backgroundColor = [UIColor clearColor];
[cell.contentView addSubview:label];
}
UILabel *label = (UILabel *)[cell viewWithTag:100];
NSString *text = self.dataList[indexPath.row];
label.text = text;
// 計算 Label 理想尺寸
CGSize maxSize = CGSizeMake(tableView.frame.size.width - 20, CGFLOAT_MAX);
CGSize labelSize = [text boundingRectWithSize:maxSize
options:NSStringDrawingUsesLineFragmentOrigin
attributes:@{NSFontAttributeName: label.font}
context:nil].size;
// 更新 Label Frame
label.frame = CGRectMake(10, 10, labelSize.width, labelSize.height);
// 計算 Cell 高度 = Label 高度 + 上下間距
CGFloat cellHeight = labelSize.height + 20;
cell.frame = CGRectMake(0, 0, tableView.frame.size.width, cellHeight);
return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
NSString *text = self.dataList[indexPath.row];
CGSize maxSize = CGSizeMake(tableView.frame.size.width - 20, CGFLOAT_MAX);
CGSize labelSize = [text boundingRectWithSize:maxSize
options:NSStringDrawingUsesLineFragmentOrigin
attributes:@{NSFontAttributeName: [UIFont systemFontOfSize:14]}
context:nil].size;
return labelSize.height + 20; // 與 cellForRow 邏輯完全一致
}
**強烈推薦**使用 Auto Layout 讓系統自動計算,零代碼計算高度:
contentView。numberOfLines = 0。self.tableView.estimatedRowHeight = 80;self.tableView.rowHeight = UITableViewAutomaticDimension;- (void)viewDidLoad {
[super viewDidLoad];
self.tableView.estimatedRowHeight = 80;
self.tableView.rowHeight = UITableViewAutomaticDimension;
// 確保 Cell 內部約束完整鏈接上下邊緣
}
cellForRow 會導致遞歸死循環,必須獨立計算。Texture (AsyncDisplayKit) 異步渲染。heightForRow 返回固定值而內容實際更高 → 內容截斷。contentView 底部 → Auto Layout 無法計算高度。separatorInset、layoutMargins 影響實際可用寬度。動態行高是列表流暢體驗的基石,Auto Layout 讓它變得簡單可靠。