How can I center rows in UICollectionView?

前端 未结 9 1592
囚心锁ツ
囚心锁ツ 2021-02-02 06:24

I have a UICollectionView with random cells. Is there any method that allows me to center rows?

This is how it looks by default:

[ x x x x         


        
9条回答
  •  深忆病人
    2021-02-02 07:03

    Swift 3.0 version of the class:

    class UICollectionViewFlowCenterLayout: UICollectionViewFlowLayout {
        override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
            guard let suggestedAttributes = super.layoutAttributesForElements(in: rect) else { return nil }
    
            guard scrollDirection == .vertical else { return suggestedAttributes }
    
            var newAttributes: [UICollectionViewLayoutAttributes] = []
    
            var currentRowAttributes: [UICollectionViewLayoutAttributes] = []
            var yOffset:CGFloat = sectionInset.top
            for attributes in suggestedAttributes {
                if attributes.frame.origin.y != yOffset {
                    centerSingleRowWithItemsAttributes(attributes: ¤tRowAttributes, rect: rect)
                    newAttributes += currentRowAttributes
                    currentRowAttributes = []
                    yOffset = attributes.frame.origin.y
                }
                currentRowAttributes += [attributes]
            }
            centerSingleRowWithItemsAttributes(attributes: ¤tRowAttributes, rect: rect)
            newAttributes += currentRowAttributes
    
            return newAttributes
        }
    
    
        private func centerSingleRowWithItemsAttributes( attributes: inout [UICollectionViewLayoutAttributes], rect: CGRect) {
            guard let item = attributes.last else { return }
    
            let itemsCount = CGFloat(attributes.count)
            let sideInsets = rect.width - (item.frame.width * itemsCount) - (minimumInteritemSpacing * (itemsCount - 1))
            var leftOffset = sideInsets / 2
    
            for attribute in attributes {
                attribute.frame.origin.x = leftOffset
                leftOffset += attribute.frame.width + minimumInteritemSpacing
            }
        }
    }
    

提交回复
热议问题