เพื่อให้ TableView cell ปรับความสูงตามเนื้อหา (auto-sizing) ใช้ UITableView.automaticDimension พร้อม estimatedRowHeight
ขั้นตอนการตั้งค่า
1. ตั้งค่า TableView
func initTableView() {
let tableView = UITableView()
tableView.frame = self.view.frame
tableView.dataSource = self
tableView.delegate = self
tableView.backgroundColor = .gray
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
tableView.estimatedRowHeight = UITableView.automaticDimension
self.view.addSubview(tableView)
}
2. กำหนดจำนวน Section และ Row
func numberOfSections(in tableView: UITableView) -> Int { return 1 }
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 5 }
3. กำหนดความสูงเป็น automaticDimension
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableView.automaticDimension
}
4. สำคัญ: ตั้ง numberOfLines ของ label = 0
UILabel ใน cell ต้องตั้ง numberOfLines = 0 เพื่อให้ขยายได้หลายบรรทัด
ผลลัพธ์
Cell ที่มีข้อความยาวจะขยายความสูงอัตโนมัติ ตามขนาดเนื้อหา
รูปภาพตัวอย่าง UI ถูกละเว้น