iOS 如何实现UICollectionView的Cell左对齐

如果想要在UICollectionView中左对齐,设置一下Cell之间的最大间距即可(因为layout只设置了最小间距,所以如果Cell填充不满,间距就会自动增大,这时就需要我们来设置一下最大间距)

import UIKit

class LeftEqualFlowLayout: UICollectionViewFlowLayout {

    // 左对齐等间距布局 (设置了最大间距)
    override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
        let answer = super.layoutAttributesForElements(in: rect)
        for (index,value) in (answer?.enumerated())!
        {
            if index > 0{
                let currentLayoutAttributes :UICollectionViewLayoutAttributes = value
                let prevLayoutAttributes:UICollectionViewLayoutAttributes = answer![index - 1]
                let maximumSpacing = 15 //这里设置最大间距
                let origin = prevLayoutAttributes.frame.maxX
                if(origin + CGFloat(maximumSpacing) + currentLayoutAttributes.frame.size.width < self.collectionViewContentSize.width) {
                    var frame = currentLayoutAttributes.frame;
                    frame.origin.x = origin + CGFloat(maximumSpacing);
                    currentLayoutAttributes.frame = frame;
                }
            }
        }
        return answer
    }
}

只需新建一个UICollectionViewFlowLayout,重写他的 layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? 方法即可

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容