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

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

    You need to conform to UICollectionViewDelegateFlowLayout protocol to find the collectionView(_:layout:insetForSectionAt:) method, it is defined there. the following implementation works fine in swift 4 for a horizontal collectionView

    extension YourViewController: UICollectionViewDelegateFlowLayout {
        func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
            let cellWidth = CGFloat(integerLiteral: YourCellsWidth)
            let count = self.YourCollectionViewDataSource.count
            let top = CGFloat(integerLiteral: 0)    // I don't need to set top and bottom spacing
            let cellsAccumulatedWidth = CGFloat(integerLiteral: count) * cellWidth
            let cellsSpacingAccumulatedWidth = CGFloat(integerLiteral: (count - 1) * 5)
            let left = (self.collectionView.frame.size.width - cellsAccumulatedWidth - cellsSpacingAccumulatedWidth) / 2
            let bottom = top
            let right = left
    
            return UIEdgeInsetsMake(top, left, bottom, right);
        }
    }
    

提交回复
热议问题