美文网首页闻道丶iOS(尝鲜版)iOS Developer
设置UICollectionView最大间距

设置UICollectionView最大间距

作者: BeSt2wazi | 来源:发表于2017-03-23 10:37 被阅读0次
    最近在项目中遇到设置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最大间距

        本文链接:https://www.haomeiwen.com/subject/zirznttx.html