Swift 專案中,UITableViewCell 內含多行 UILabel,需根據文字長度自動調整高度。提問者已設定 tableView.rowHeight = UITableViewAutomaticDimension 但未生效。
numberOfLines = 0:允許無限換行。tableView.estimatedRowHeight = 44(提升滾動效能)。cellForRow 手動設定 cell.frame.size.height:會干擾自動計算。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,減少手動計算錯誤。