UICollectionView 的布局默認是當前行內適應枷畏,如果cell的寬度超過當前的行寬度就會放到下一行认轨,但是當前行內的多個cell會等距離分布很钓,而不能像效果圖中等間距靠left 或者right分布纸淮。
/// 讓列間距固定為minimumInteritemSpacing
class AiUgcReportFlowLayout: UICollectionViewFlowLayout {
override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
if let attris = super.layoutAttributesForElements(in: rect) {
for (i, att) in attris.enumerated() {
if i>0 {
let cur = att
let pre = attris[i-1]
// 這里 indexPath 一定要判斷袱院,坑了半天屎慢,fuck
if cur.indexPath == pre.indexPath {
let preMaxX = pre.frame.maxX
//根據 maximumInteritemSpacing 計算出的新的 x 位置
let targetX = preMaxX + self.minimumInteritemSpacing;
if targetX < cur.frame.maxX && (targetX+cur.frame.width) < self.collectionViewContentSize.width {
var curFrame = cur.frame
curFrame.origin.x = targetX
cur.frame = curFrame
}
}
}
}
return attris
}
return super.layoutAttributesForElements(in: rect)
}
}
?? ?? ?? ?? 提供oc 版本,直接用吧騷年?? ?? ??
- (NSArray<__kindof UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect {
NSArray *attris = [super layoutAttributesForElementsInRect:rect];
for (int i = 0; i< attris.count; i++) {
if (i>0) {
UICollectionViewLayoutAttributes *curAtt = attris[i];
UICollectionViewLayoutAttributes *preAtt = attris[i-1];
// 這里 indexPath 一定要判斷忽洛,坑了半天腻惠,fuck
if (curAtt.indexPath == preAtt.indexPath) {
CGFloat curMaxX = curAtt.frame.origin.x+curAtt.frame.size.width;
CGFloat preMaxX = preAtt.frame.origin.x+preAtt.frame.size.width;
CGFloat targetX = preMaxX + self.minimumInteritemSpacing;
if ((targetX < curMaxX) && (targetX+curAtt.frame.size.width) < self.collectionView.bounds.size.width) {
CGRect curFrame = curAtt.frame;
curFrame.origin.x = targetX;
curAtt.frame = curFrame;
}
}
}
}
return attris;
}