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

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

    This code should center horizontally any type of collection view even with extra items in Swift 4.0:

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
        let flowLayout = collectionViewLayout as! UICollectionViewFlowLayout
        let cellWidth: CGFloat = flowLayout.itemSize.width
        let cellSpacing: CGFloat = flowLayout.minimumInteritemSpacing
        let cellCount = CGFloat(collectionView.numberOfItems(inSection: section))
        var collectionWidth = collectionView.frame.size.width
        if #available(iOS 11.0, *) {
            collectionWidth -= collectionView.safeAreaInsets.left + collectionView.safeAreaInsets.right
        }
        let totalWidth = cellWidth * cellCount + cellSpacing * (cellCount - 1)
        if totalWidth <= collectionWidth {
            let edgeInset = (collectionWidth - totalWidth) / 2
            return UIEdgeInsetsMake(flowLayout.sectionInset.top, edgeInset, flowLayout.sectionInset.bottom, edgeInset)
        } else {
            return flowLayout.sectionInset
        }
    }
    

    Don't forget if you are not subclassing UICollectionViewController, make sure your class conforms to UICollectionViewDelegateFlowLayout protocol

提交回复
热议问题