問(wèn)題描述:
Collection View 的cell 根據(jù)內(nèi)容調(diào)整高度(或?qū)挾龋瑢?shí)現(xiàn)瀑布流布局。
解決方案:
原生的 FlowLayout 顯然不行,只有繼承自 UICollectionViewLayout,使用自定義布局。步驟如下:
- 實(shí)現(xiàn) prepare() 方法。主要計(jì)算每一個(gè)cell 的 layout attribute 和 collection view 的 content size。如果內(nèi)容較少,可以緩存計(jì)算出的 layout attribute,方便復(fù)用。
- 實(shí)現(xiàn) collectionViewContentSize 方法。提供由上一步計(jì)算出的content size。
- 實(shí)現(xiàn) layoutAttributesForElements(in:) 方法。提供與顯示區(qū)域相交的 layout attribute。
- 實(shí)現(xiàn) layoutAttributesForItem(at:) 方法。提供與 indexPath 對(duì)應(yīng)的 layout attribute。