How to center align the cells of a UICollectionView in Swift3.0?

后端 未结 11 2063
不知归路
不知归路 2021-02-14 11:25

Description:

Answer for Objective-C and Swift2.0: How to center align the cells of a UICollectionView?

I usually would try to conver

11条回答
  •  别那么骄傲
    2021-02-14 11:50

    Use this solution for horizontal scrolling with the center align.

    let totalCellWidth = Int(collectionView.frame.height * CGFloat(numberOfItems()))
    
            // if total width is greater than collection's width, then no need to align center
            if totalCellWidth > Int(collectionView.frame.width) {
                return UIEdgeInsets.zero
            }
    
            let totalSpacingWidth = cellSpacing * (numberOfItems() - 1)
            let leftInset = (collectionView.frame.width - CGFloat(totalCellWidth + totalSpacingWidth)) / 2
            let rightInset = leftInset
            return UIEdgeInsets(top: 0, left: leftInset, bottom: 0, right: rightInset)
    

提交回复
热议问题