萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> iOS 開發

iOS UITableView Cell 動態高度自適應完整實現

實現 Cell 高度隨內容自適應,核心在於 heightForRowAtIndexPath 與 cellForRowAtIndexPath 返回一致的高度計算邏輯。本文提供基於 UILabel sizeToFit 的經典方案(iOS 7+ 推薦使用 Auto Layout 自動計算)。

核心代碼結構

1. 數據模型

@interface ViewController () 
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *dataList; // 存儲不同長度的字符串
@end

2. Cell 配置與高度計算

- (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;
}

3. 返回一致的行高

- (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 自動行高 (iOS 8+)

**強烈推薦**使用 Auto Layout 讓系統自動計算,零代碼計算高度:

  1. Cell 內容視圖添加上下左右約束到 contentView。
  2. Label 設置 numberOfLines = 0。
  3. 設置預估行高:self.tableView.estimatedRowHeight = 80;
  4. 啟用自動行高:self.tableView.rowHeight = UITableViewAutomaticDimension;
- (void)viewDidLoad {
    [super viewDidLoad];
    self.tableView.estimatedRowHeight = 80;
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    // 確保 Cell 內部約束完整鏈接上下邊緣
}

性能優化要點

  • 預估行高准確:減少佈局計算次數。
  • 避免 heightForRow 中創建 Cell:舊代碼中調用 cellForRow 會導致遞歸死循環,必須獨立計算。
  • 緩存高度:異構列表可預先計算緩存高度字典。
  • 異步佈局:極長文本考慮 Texture (AsyncDisplayKit) 異步渲染。

避坑清單

  • ❌ heightForRow 返回固定值而內容實際更高 → 內容截斷。
  • ❌ Label 約束未貫穿到 contentView 底部 → Auto Layout 無法計算高度。
  • ❌ 忽略 separatorInset、layoutMargins 影響實際可用寬度。
  • ✅ 統一計算邏輯、優先 Auto Layout、實測邊界情況(空文本、超長單詞、Emoji)。

動態行高是列表流暢體驗的基石,Auto Layout 讓它變得簡單可靠。

copyright © 萬盛學電腦網 all rights reserved