如果想要在UICollectionView中左对齐,设置一下Cell之间的最大间距即可(因为layout只设置了最小间距,所以如果Cell填充不满,间距就会自动增大,这时就需要我们来设置一下最大间距)
import UIKit
class LeftEqualFlowLayout: UICollectionViewFlowLayout {
// 左对齐等间距布局 (设置了最大间距)
override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
let answer = super.layoutAttributesForElements(in: rect)
for (index,value) in (answer?.enumerated())!
{
if index > 0{
let currentLayoutAttributes :UICollectionViewLayoutAttributes = value
let prevLayoutAttributes:UICollectionViewLayoutAttributes = answer![index - 1]
let maximumSpacing = 15 //这里设置最大间距
let origin = prevLayoutAttributes.frame.maxX
if(origin + CGFloat(maximumSpacing) + currentLayoutAttributes.frame.size.width < self.collectionViewContentSize.width) {
var frame = currentLayoutAttributes.frame;
frame.origin.x = origin + CGFloat(maximumSpacing);
currentLayoutAttributes.frame = frame;
}
}
}
return answer
}
}
只需新建一个UICollectionViewFlowLayout,重写他的 layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? 方法即可