如果想要在UICollectionView中左對齊,設(shè)置一下Cell之間的最大間距即可(因?yàn)閘ayout只設(shè)置了最小間距,所以如果Cell填充不滿,間距就會自動增大,這時(shí)就需要我們來設(shè)置一下最大間距)
import UIKit
class LeftEqualFlowLayout: UICollectionViewFlowLayout {
// 左對齊等間距布局 (設(shè)置了最大間距)
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 //這里設(shè)置最大間距
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
}
}
只需新建一個(gè)UICollectionViewFlowLayout边器,重寫他的 layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? 方法即可