this is a pretty straightforward question, but I haven\'t been able to find a definitive answer to it on SO (if I missed it, please correct me).
Basically, my quest
From what I can tell, all of these answers want to fill the collection view from right to left. For example, if you labeled cells 1, 2, 3, then they would appear in the order 3, 2, 1 in the collection view. In my case I wanted the cells to appear in the order 1, 2, 3 (like text right alignment when the line is not full). In order to do this I created a simple UICollectionViewFlow layout.
import UIKit
class RightAlignFlowLayout: UICollectionViewFlowLayout {
override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]?
{
guard let attrsArr = super.layoutAttributesForElements(in: rect) else {
return nil
}
guard let collectionView = self.collectionView else { return attrsArr }
if self.collectionViewContentSize.width > collectionView.bounds.width {
return attrsArr
}
let remainingSpace = collectionView.bounds.width - self.collectionViewContentSize.width
for attr in attrsArr {
attr.frame.origin.x += remainingSpace
}
return attrsArr
}
override func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
guard let attrs = super.layoutAttributesForItem(at: indexPath) else { return nil }
guard let collectionView = self.collectionView else { return attrs }
if self.collectionViewContentSize.width > collectionView.bounds.width {
return attrs
}
let remainingSpace = collectionView.bounds.width - self.collectionViewContentSize.width
attrs.frame.origin.x += remainingSpace
return attrs
}
}