实现思路:
1)设置layout的estimatedItemSize属性
flowLayout.estimatedItemSize = CGSize(width: UIScreen.main.bounds.width, height: 50)
2)为cell内部的view控件添加上下约束,保证竖直高度被撑满
3)重写preferredLayoutAttributesFitting方法,重新计算cell的高度
override func preferredLayoutAttributesFitting(_ layoutAttributes: UICollectionViewLayoutAttributes) -> UICollectionViewLayoutAttributes {
self.setNeedsLayout()
self.layoutIfNeeded()
// 重新计算contentView的高度
let size = self.contentView.systemLayoutSizeFitting(layoutAttributes.size)
var cellFrame = layoutAttributes.frame
cellFrame.size.height = size.height
layoutAttributes.frame = cellFrame
return layoutAttributes
}
务必注意:要把cell内部的view添加到cell的self.contentView上才能高度自适应,直接添加到self上不行!!!
实现效果: