设置UICollectionView最大间距

最近在项目中遇到设置CollectionView左对齐的问题,就想到了设置CollectionView最大间距即可解决左对齐的问题,话不多说,直接上代码
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 = 10
            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]? 方法即可

你可能感兴趣的:(设置UICollectionView最大间距)