I am trying to create a UICollectionView with cells that have varying widths but constant heights. The UICollectionView has 3 rows and scrolls horizontally.
Each cell should have 8px between the next cell to it's right and the row below. I have set this as the minimum spacing in IB.
When I have the scrolling set to vertical the following code works, all cells get aligned to left and the spacing is 8px between all cells. However if this code is used when scrolling is horizontal, this does not work.
Any direction would be greatly appreciated.
class HorizontalCollectionViewFlowLayout: UICollectionViewFlowLayout {
override init(){
super.init()
scrollDirection = .horizontal
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)!
self.scrollDirection = .horizontal
}
override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
let attributes = super.layoutAttributesForElements(in: rect)
var leftMargin = sectionInset.left
var maxY: CGFloat = -1.0
attributes?.forEach { layoutAttribute in
if layoutAttribute.frame.origin.y >= maxY {
leftMargin = sectionInset.left
}
layoutAttribute.frame.origin.x = leftMargin
leftMargin += layoutAttribute.frame.width + minimumInteritemSpacing
maxY = max(layoutAttribute.frame.maxY , maxY)
}
return attributes
}
}
Edit: This is the UI that I am trying to achieve.