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

后端 未结 11 2065
不知归路
不知归路 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:32

    Here's a recent solution, works for Swift 5.0

    extension YourViewController: UICollectionViewDelegateFlowLayout {
        func collectionView(_ collectionView: UICollectionView,
                            layout collectionViewLayout: UICollectionViewLayout,
                            insetForSectionAt section: Int) -> UIEdgeInsets {
            let itemWidth = 80
            let spacingWidth = 4
            let numberOfItems = collectionView.numberOfItems(inSection: section)
            let cellSpacingWidth = numberOfItem * spacingWidth
            let totalCellWidth = numberOfItems * itemWidth + cellSpacingWidth
            let inset = (collectionView.layer.frame.size.width - CGFloat(totalCellWidth)) / 2
            return UIEdgeInsets(top: 5, left: inset, bottom: 5, right: inset)
        }
    }
    

提交回复
热议问题