Cell spacing in UICollectionView

后端 未结 26 3739
旧巷少年郎
旧巷少年郎 2020-11-22 15:53

How do I set cell spacing in a section of UICollectionView? I know there is a property minimumInteritemSpacing I have set it to 5.0 still the spaci

26条回答
  •  盖世英雄少女心
    2020-11-22 16:33

    The above solution by vojtech-vrbka is correct but it triggers a warning:

    warning:UICollectionViewFlowLayout has cached frame mismatch for index path - cached value: This is likely occurring because the flow layout subclass Layout is modify attributes returned by UICollectionViewFlowLayout without copying them

    The following code should fix it:

    class CustomViewFlowLayout : UICollectionViewFlowLayout {
    
       let cellSpacing:CGFloat = 4
    
       override func layoutAttributesForElementsInRect(rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
           let original = super.layoutAttributesForElementsInRect(rect)
    
           if let original = original {
               let attributes = NSArray.init(array: original, copyItems: true) as! [UICollectionViewLayoutAttributes]
    
               for (index, attribute) in attributes.enumerate() {
                    if index == 0 { continue }
                    let prevLayoutAttributes = attributes[index - 1]
                    let origin = CGRectGetMaxX(prevLayoutAttributes.frame)
                    if(origin + cellSpacing + attribute.frame.size.width < self.collectionViewContentSize().width) {
                        attribute.frame.origin.x = origin + cellSpacing
                    }
                }
                return attributes
           }
           return nil
       }
    }
    

提交回复
热议问题