How to center align the cells of a UICollectionView?

前端 未结 18 2465
梦如初夏
梦如初夏 2020-11-28 01:33

I am currently using UICollectionView for the user interface grid, and it works fine. However, I\'d like to be enable horizontal scrolling. The grid supports 8

18条回答
  •  遥遥无期
    2020-11-28 01:57

    Put this into your collection view delegate. It considers more of the the basic flow layout settings than the other answers and is thereby more generic.

    - (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
    {
        NSInteger cellCount = [collectionView.dataSource collectionView:collectionView numberOfItemsInSection:section];
        if( cellCount >0 )
        {
            CGFloat cellWidth = ((UICollectionViewFlowLayout*)collectionViewLayout).itemSize.width+((UICollectionViewFlowLayout*)collectionViewLayout).minimumInteritemSpacing;
            CGFloat totalCellWidth = cellWidth*cellCount + spacing*(cellCount-1);
            CGFloat contentWidth = collectionView.frame.size.width-collectionView.contentInset.left-collectionView.contentInset.right;
            if( totalCellWidth

    swift version (thanks g0ld2k):

    extension CommunityConnectViewController: UICollectionViewDelegateFlowLayout {
        func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAtIndex section: Int) -> UIEdgeInsets {
    
        // Translated from Objective-C version at: http://stackoverflow.com/a/27656363/309736
    
            let cellCount = CGFloat(viewModel.getNumOfItemsInSection(0))
    
            if cellCount > 0 {
                let flowLayout = collectionViewLayout as! UICollectionViewFlowLayout
                let cellWidth = flowLayout.itemSize.width + flowLayout.minimumInteritemSpacing
                let totalCellWidth = cellWidth*cellCount + spacing*(cellCount-1)
                let contentWidth = collectionView.frame.size.width - collectionView.contentInset.left - collectionView.contentInset.right
    
                if (totalCellWidth < contentWidth) {
                    let padding = (contentWidth - totalCellWidth) / 2.0
                    return UIEdgeInsetsMake(0, padding, 0, padding)
                }
            }
    
            return UIEdgeInsetsZero
        }
    }
    

提交回复
热议问题