How to center align the cells of a UICollectionView?

前端 未结 18 2468
梦如初夏
梦如初夏 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 02:04

    Similar to other answers, this is a dynamic answer that should work for static sized cells. The one modification I made is that I put the padding on both sides. If I didn't do this, I experienced problems.


    Objective-C

    - (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewFlowLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
    
        NSInteger numberOfItems = [collectionView numberOfItemsInSection:section];
        CGFloat combinedItemWidth = (numberOfItems * collectionViewLayout.itemSize.width) + ((numberOfItems - 1) * collectionViewLayout.minimumInteritemSpacing);
        CGFloat padding = (collectionView.frame.size.width - combinedItemWidth) / 2;
    
        return UIEdgeInsetsMake(0, padding, 0, padding);
    }
    

    Swift

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
        let flowLayout = collectionViewLayout as! UICollectionViewFlowLayout
        let numberOfItems = CGFloat(collectionView.numberOfItems(inSection: section))
        let combinedItemWidth = (numberOfItems * flowLayout.itemSize.width) + ((numberOfItems - 1)  * flowLayout.minimumInteritemSpacing)
        let padding = (collectionView.frame.width - combinedItemWidth) / 2
        return UIEdgeInsets(top: 0, left: padding, bottom: 0, right: padding)
    }
    

    Also, if you are still are experiencing problems, make sure that you set both the minimumInteritemSpacing and minimumLineSpacing to the same values since these values seem to be interrelated.

    UICollectionViewFlowLayout *flowLayout = (UICollectionViewFlowLayout *)self.collectionView.collectionViewLayout;
    flowLayout.minimumInteritemSpacing = 20.0;
    flowLayout.minimumLineSpacing = 20.0;
    

提交回复
热议问题