Cell spacing in UICollectionView

后端 未结 26 3738
旧巷少年郎
旧巷少年郎 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:28

    Swift version of the most popular answer. Space between the cells will be equal to cellSpacing.

    class CustomViewFlowLayout : UICollectionViewFlowLayout {
    
        let cellSpacing:CGFloat = 4
    
        override func layoutAttributesForElementsInRect(rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
            if let attributes = super.layoutAttributesForElementsInRect(rect) {
            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
        }
    }
    

提交回复
热议问题