声明一下,本人只是把下面的文章改成了swift版本而已,方便以后直接用。
效果图如下

创建一个layout为CustomClvFlowLayout,然后设置maximumInteritemSpacing为自己的需求即可了。
let layout = LLCustomClvFlowLayout()
layout.maximumInteritemSpacing = 10.0
class CustomClvFlowLayout: UICollectionViewFlowLayout {
var maximumInteritemSpacing: CGFloat = 0.0
override func prepare() {
super.prepare()
}
override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
super.layoutAttributesForElements(in: rect)
//使用系统帮我们计算好的结果
guard let attributes = super.layoutAttributesForElements(in: rect) else {
return nil
}
//第0个cell没有上一个cell,所以从1开始
for i in 1..<attributes.count {
let curAttr = attributes[i]
let preAttr = attributes[i-1]
let origin = preAttr.frame.maxX
//根据maximumInteritemSpacing计算出的新的x位置
let targetX = origin + maximumInteritemSpacing
//只有系统计算的间距大于maximumInteritemSpacing时才进行调整
if curAttr.frame.minX > targetX {
// 换行时不用调整
if targetX + curAttr.frame.width < collectionViewContentSize.width {
var frame = curAttr.frame
frame.origin.x = targetX
curAttr.frame = frame
}
}
}
return attributes
}
}
网友评论