I'm trying to create a horizontal UICollectionView with possibility to align part of cells to the left side and other part to the right. Between right and left cells should be empty space. Is it possible using UICollectionView and UICollectionViewFlowLayout?
I tried this version of UICollectionViewFlowLayout but it doesn't work properly. I'm trying to understand how to calculate offset dynamically.
class LeftRightAlignedCollectionViewFlowLayout: UICollectionViewFlowLayout {
var offset: CGFloat = 30
fileprivate var layoutAttributes = [UICollectionViewLayoutAttributes]()
fileprivate var contentSize = CGSize.zero
override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
guard let superAttributes = super.layoutAttributesForElements(in: rect) else { return nil }
var attributes = superAttributes
let centerX = collectionView!.contentOffset.x + collectionView!.bounds.width / 2.0
for attribute in attributes {
let distance = abs(attribute.center.x - centerX)
let offset = min(abs(distance), self.offset)
let factor = (self.offset - offset) / self.offset
let translation = factor * attribute.size.width / 2
attribute.center.x += distance < self.offset ? (attribute.center.x < centerX ? -translation : translation) : 0
}
return attributes
}
override func shouldInvalidateLayout(forBoundsChange newBounds: CGRect) -> Bool {
return true
}
}