菜鳥iOS工程師上工第一彈|TableView Cell Dynamic Height

CollectionView inside TableView Cell Dynamic Height

自今年七月成功轉職至今,來到九月中下旬,晃眼入職將滿三個月 🙌🏻 在滿兩個月前,每天不停讀著文件看著前人寫的肥大MVC文件,隨便拉一個VC 上看二三四五千行的技術債…(咳咳咳,菜鳥認命吧🙃)

幸運的,公司其他 iOS 工程師前輩都非常好相處,願意傳授葵花寶典,也都能在每個月的 iOS Code Review 中學到很多好招!

🔍 OKay!進入正題 ⋯

(此篇 View 都以 XIB 生成)

關於 Table View 的動態高 (自動計算高) UITableView.automaticDimension 行之有年想必大家肯定不陌生,但當 Table View Cell 加入 Collection View 光是給UITableView.automaticDimension 去計算高度可是不夠的。

上方圖為實際操作 Collection View 依內容高度撐起 Table View Cell 顯示畫面,Collection View 內容為 API 控制,因此無法將 Cell 高度直接寫死。如要手動依內容數量計算高度當然也是可以,但這太不智慧了😌 … 在我還不會接下來的方法前,我就是直接計算內容數量硬幹 Table View Cell 的高啊 🤣

因 Code 為公司資產,因此做了一個極簡Demo版本,程式碼分享在文末。下左圖為未成功將collectionView撐起,右圖為成功撐起之畫面。

A CollectionView inside a TableViewCell which with a bunch of collectionViewCells

AutoLayout, Delegate, DataSource, FlowLayout 等等的前置基本作業不贅述。

TableView

在 VC 裏,對 TableView heightForRowAt 設動態高(自動計算高) UITableView.automaticDimension

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableView.automaticDimension
}

TableViewCell

在 tableViewCell 裏,將 collectionView 的滾動功能關閉 collectionView.isScrollEnabled = false
systemLayoutSizeFitting 設定 tableViewCell 的大小 = self.bounds
呼叫layoutIfNeeded() 並回傳 collectionView.contentSize

完成此步驟即大功告成 👍🏻

override func awakeFromNib() {
super.awakeFromNib()
collectionView.isScrollEnabled = false
}

override func systemLayoutSizeFitting(_ targetSize: CGSize, withHorizontalFittingPriority horizontalFittingPriority: UILayoutPriority, verticalFittingPriority: UILayoutPriority) -> CGSize {
self.contentView.frame = self.bounds
self.contentView.layoutIfNeeded()
return collectionView.contentSize
}

Demo Github 連結

--

--