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

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

    Slight adaptation of @rottenoats answer. This is more generic.

    Most importantly remember to make your view controller conform to the UICollectionViewDelegateFlowLayout protocol.

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
    
        guard let flowLayout = collectionViewLayout as? UICollectionViewFlowLayout else {
            return .zero
        }
    
        let cellCount = CGFloat(collectionView.numberOfItems(inSection: section))
    
        if cellCount > 0 {
            let cellWidth = flowLayout.itemSize.width + flowLayout.minimumInteritemSpacing
    
            let totalCellWidth = cellWidth * cellCount
            let contentWidth = collectionView.frame.size.width - collectionView.contentInset.left - collectionView.contentInset.right - flowLayout.headerReferenceSize.width - flowLayout.footerReferenceSize.width
    
            if (totalCellWidth < contentWidth) {
                let padding = (contentWidth - totalCellWidth + flowLayout.minimumInteritemSpacing) / 2.0
                return UIEdgeInsetsMake(0, padding, 0, 0)
            }
        }
    
        return .zero
    }
    

提交回复
热议问题