首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

iOS Swift UITableViewCell 自適應高度:Autolayout + rowHeight = AutomaticDimension

     編輯:程式設計綜合問答

Swift 專案中,UITableViewCell 內含多行 UILabel,需根據文字長度自動調整高度。提問者已設定 tableView.rowHeight = UITableViewAutomaticDimension 但未生效。

關鍵檢查清單

  1. Cell 使用 Auto Layout:所有子視圖(Label)需有完整約束(上、下、左、右),讓系統能計算內容高度。
  2. Label 設定 numberOfLines = 0:允許無限換行。
  3. 提供預估高度:tableView.estimatedRowHeight = 44(提升滾動效能)。
  4. 不要在 cellForRow 手動設定 cell.frame.size.height:會干擾自動計算。
  5. 若用 XIB/Storyboard:確認 Cell 的 Content View 底部約束連接到最後一個 Label 的底部。

補充:手動計算高度(舊版相容)

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    let text = data[indexPath.row]
    let width = tableView.bounds.width - 32 // 扣除左右間距
    let font = UIFont.systemFont(ofSize: 16)
    let rect = text.boundingRect(with: CGSize(width: width, height: .greatestFiniteMagnitude),
                                 options: .usesLineFragmentOrigin,
                                 attributes: [.font: font],
                                 context: nil)
    return ceil(rect.height) + 20 // 加上上下 padding
}

iOS 8+ 建議全面採用 AutomaticDimension,減少手動計算錯誤。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved