iOS - UICollectionView spacing still there when set to 0 - How to set with no spacing between cells

前端 未结 6 1445
南旧
南旧 2020-12-16 12:03

I have a simple UICollectionView which I have set with 0 spacing in InterfaceBuilder but when I populate the collection view with cells there is still some spacing. Is there

6条回答
  •  被撕碎了的回忆
    2020-12-16 12:45

    You have to create custom UICollectionViewLayout.

    Space between the cells will be equal to cellSpacing.

    final class CustomFlowLayout: UICollectionViewFlowLayout {
    
        let cellSpacing: CGFloat = 0
    
        override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
            if let attributes = super.layoutAttributesForElements(in: rect) {
                for (index, attribute) in attributes.enumerated() {
                    if index == 0 { continue }
                    let prevLayoutAttributes = attributes[index - 1]
                    let origin = prevLayoutAttributes.frame.maxX
                    if (origin + cellSpacing + attribute.frame.size.width < self.collectionViewContentSize.width) {
                        attribute.frame.origin.x = origin + cellSpacing
                    }
                }
                return attributes
            }
            return nil
        }
    
    }
    

提交回复
热议问题