自從 iOS 8 以后, 自適應(yīng)高度的 cell 就變得非常簡單. 只需要兩步就可以做到了:
給 cell 設(shè)置合適的約束, 合適的約束是指, 根據(jù)約束你可以算出具體的高度. 具體的可以參考官方文檔
設(shè)置將 TableView 的 rowHeight 設(shè)為UITableViewAutomaticDimension. 并設(shè)置合理的 estimatedRowHeight. 對于多種類型的 Cell 的 TableView 可能需要對不同的 cell 設(shè)置不同的estimatedRowHeight. 這個(gè)時(shí)候可以通過實(shí)現(xiàn) UITableViewDelegate 的兩個(gè)方法來實(shí)現(xiàn):
func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat
注意事項(xiàng)
當(dāng)高度變成自適應(yīng)后不代表你就需要在關(guān)注單元格的高度, Apple 的官方文檔強(qiáng)調(diào) estimatedRowHeight 設(shè)置得越精確越好. 因?yàn)橄到y(tǒng)需要利用 estimatedRowHeight 來計(jì)算滾動條的高度和位置等數(shù)據(jù). 如果你提供的預(yù)估高度跟實(shí)際問題就可以導(dǎo)致一些滾動上的問題, 影響用戶體驗(yàn).