Self-Sizing Cell
设置预估大小
layout.estimatedItemSize=CGSize(width:100, height:25)
重写cell方法
override func preferredLayoutAttributesFitting(_ layoutAttributes: UICollectionViewLayoutAttributes) -> UICollectionViewLayoutAttributes {
setNeedsLayout()
layoutIfNeeded()
let size = contentView.systemLayoutSizeFitting(layoutAttributes.size)
var newFrame = layoutAttributes.frame
//限制宽度最大为100
newFrame.size.width = size.width > 100 ? 100 : ceil(size.width)
newFrame.size.height = ceil(size.height)
layoutAttributes.frame = newFrame
return layoutAttributes
}
这时候显示的是这样
而我们想要实现每个cell以最小间距紧密排列
左对齐
复杂的方法是自己写一个UICollectionViewLayout,这里我选择了一种更简单的方法,根据系统的布局来进行调整,创建一个UICollectionViewLeftFlowLayout类继承UICollectionViewFlowLayout,重写layoutAttributesForElements(in rect:CGRect)方法
class UICollectionViewLeftFlowLayout: UICollectionViewFlowLayout {
override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
guard let attrsArry = super.layoutAttributesForElements(in: rect) else {
return nil
}
for i in 0..<attrsArry.count {
if i != attrsArry.count-1 {
let curAttr = attrsArry[i] //当前attr
let nextAttr = attrsArry[i+1] //下一个attr
//如果下一个在同一行则调整,不在同一行则跳过
if curAttr.frame.minY == nextAttr.frame.minY {
if nextAttr.frame.minX - curAttr.frame.maxX > minimumInteritemSpacing{
var frame = nextAttr.frame
let x = curAttr.frame.maxX + minimumInteritemSpacing
frame = CGRect(x: x, y: frame.minY, width: frame.width, height: frame.height)
nextAttr.frame = frame
}
}
}
}
return attrsArry
}
}
最终效果如下