How do you determine spacing between cells in UICollectionView flowLayout

后端 未结 12 1222
夕颜
夕颜 2020-11-29 15:32

I have a UICollectionView with a flow layout and each cell is a square. How do I determine the spacing between each cells on each row? I can\'t seem to find the appropriate

12条回答
  •  盖世英雄少女心
    2020-11-29 16:00

    A cleaner swift version for people interested, based on Chris Wagner's answer:

    class AlignLeftFlowLayout: UICollectionViewFlowLayout {
    
        var maximumCellSpacing = CGFloat(9.0)
    
        override func layoutAttributesForElementsInRect(rect: CGRect) -> [AnyObject]? {
            let attributesToReturn = super.layoutAttributesForElementsInRect(rect) as? [UICollectionViewLayoutAttributes]
    
            for attributes in attributesToReturn ?? [] {
                if attributes.representedElementKind == nil {
                    attributes.frame = self.layoutAttributesForItemAtIndexPath(attributes.indexPath).frame
                }
            }
    
            return attributesToReturn
        }
    
        override func layoutAttributesForItemAtIndexPath(indexPath: NSIndexPath) -> UICollectionViewLayoutAttributes! {
            let curAttributes = super.layoutAttributesForItemAtIndexPath(indexPath)
            let sectionInset = (self.collectionView?.collectionViewLayout as UICollectionViewFlowLayout).sectionInset
    
            if indexPath.item == 0 {
                let f = curAttributes.frame
                curAttributes.frame = CGRectMake(sectionInset.left, f.origin.y, f.size.width, f.size.height)
                return curAttributes
            }
    
            let prevIndexPath = NSIndexPath(forItem: indexPath.item-1, inSection: indexPath.section)
            let prevFrame = self.layoutAttributesForItemAtIndexPath(prevIndexPath).frame
            let prevFrameRightPoint = prevFrame.origin.x + prevFrame.size.width + maximumCellSpacing
    
            let curFrame = curAttributes.frame
            let stretchedCurFrame = CGRectMake(0, curFrame.origin.y, self.collectionView!.frame.size.width, curFrame.size.height)
    
            if CGRectIntersectsRect(prevFrame, stretchedCurFrame) {
                curAttributes.frame = CGRectMake(prevFrameRightPoint, curFrame.origin.y, curFrame.size.width, curFrame.size.height)
            } else {
                curAttributes.frame = CGRectMake(sectionInset.left, curFrame.origin.y, curFrame.size.width, curFrame.size.height)
            }
    
            return curAttributes
        }
    }
    

提交回复
热议问题