Aligning right to left on UICollectionView

前端 未结 13 693
悲哀的现实
悲哀的现实 2020-12-02 08:31

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

13条回答
  •  北荒
    北荒 (楼主)
    2020-12-02 09:03

    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
        }
    
    }
    

提交回复
热议问题