0Day Forums
Left Align Cells in UICollectionView - Printable Version

+- 0Day Forums (https://0day.red)
+-- Forum: Coding (https://0day.red/Forum-Coding)
+--- Forum: Objective-C (https://0day.red/Forum-Objective-C)
+--- Thread: Left Align Cells in UICollectionView (/Thread-Left-Align-Cells-in-UICollectionView)

Pages: 1 2 3


RE: Left Align Cells in UICollectionView - noisette522 - 07-21-2023

Based on answers here, but fixed crashes and aligning problems when your collection view is also got headers or footers. Aligning left only cells:

```swift
class LeftAlignedCollectionViewFlowLayout: UICollectionViewFlowLayout {

override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
let attributes = super.layoutAttributesForElements(in: rect)

var leftMargin = sectionInset.left
var prevMaxY: CGFloat = -1.0
attributes?.forEach { layoutAttribute in

guard layoutAttribute.representedElementCategory == .cell else {
return
}

if layoutAttribute.frame.origin.y >= prevMaxY {
leftMargin = sectionInset.left
}

layoutAttribute.frame.origin.x = leftMargin

leftMargin += layoutAttribute.frame.width + minimumInteritemSpacing
prevMaxY = layoutAttribute.frame.maxY
}

return attributes
}
}
```