Ios 收集视图中间的快速收集视图-中心单元

Ios 收集视图中间的快速收集视图-中心单元,ios,swift2,uicollectionview,uicollectionviewlayout,Ios,Swift2,Uicollectionview,Uicollectionviewlayout,我试图将UICollectionView中的所有单元格放在中间。这些单元格被划分为11x4 我已经尝试使用下面的代码,但是,单元格被分组在一行中 我试图实现的目标如第二幅图所示: 错 应该是 同样在我的代码中,我有趣地将单元格分成4行,也许我应该在这里实现居中系统,但我不知道如何实现这一点。有什么想法吗 func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollection

我试图将
UICollectionView
中的所有单元格放在中间。这些单元格被划分为11x4

我已经尝试使用下面的代码,但是,单元格被分组在一行中

我试图实现的目标如第二幅图所示:

应该是

同样在我的代码中,我有趣地将单元格分成4行,也许我应该在这里实现居中系统,但我不知道如何实现这一点。有什么想法吗

func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAtIndex section: Int) -> UIEdgeInsets {

        let totalCellWidth = 30 * 11
        let totalSpacingWidth = 2 * (11 - 1)

        let leftInset = (self.view.frame.size.width - CGFloat(totalCellWidth + totalSpacingWidth)) / 2;
        let rightInset = leftInset

        return UIEdgeInsetsMake(0, leftInset, 0, rightInset)
    }

找到解决方案:

func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAtIndex section: Int) -> UIEdgeInsets {

        let totalCellWidth = 30 * 11
        let totalSpacingWidth = 2 * (11 - 1)

        let leftInset = (self.view.frame.size.width - CGFloat(totalCellWidth + totalSpacingWidth)) / 2;
        let rightInset = leftInset

        let totalCellHeight = 30 * 4
        let totalSpacingHeight = 5 * (4 - 1)

        let topInset = (self.view.frame.size.height - CGFloat(totalCellHeight + totalSpacingHeight)) / 2;
        let bottInset = topInset

        return UIEdgeInsetsMake(topInset, leftInset, bottInset, rightInset)
    }

如果您喜欢更直观的方法,请尝试更改插图

func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAtIndex section: Int) -> UIEdgeInsets {

        let totalCellWidth = 30 * 11
        let totalSpacingWidth = 2 * (11 - 1)

        let leftInset = (self.view.frame.size.width - CGFloat(totalCellWidth + totalSpacingWidth)) / 2;
        let rightInset = leftInset

        let totalCellHeight = 30 * 4
        let totalSpacingHeight = 5 * (4 - 1)

        let topInset = (self.view.frame.size.height - CGFloat(totalCellHeight + totalSpacingHeight)) / 2;
        let bottInset = topInset

        return UIEdgeInsetsMake(topInset, leftInset, bottInset, rightInset)
    }