UICollectionViewLayout - 2 列中的 3 个单元格

Posted

技术标签:

【中文标题】UICollectionViewLayout - 2 列中的 3 个单元格【英文标题】:UICollectionViewLayout - 3 cells in 2 columns 【发布时间】:2020-02-03 17:45:39 【问题描述】:

我正在尝试创建一个具有 7 单元重复布局的 UICollectionView,如下所示:

但是,使用 CollectionViewLayout,我似乎无法将第 6 和第 7 个单元格放入同一列。

以下是相关代码:

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize 
        let collectionViewWidth = self.collectionView.bounds.width
        let flowLayout = collectionViewLayout as! UICollectionViewFlowLayout
        let spaceBetweenCells = flowLayout.minimumInteritemSpacing
        var adjustedWidth = collectionViewWidth - spaceBetweenCells

        if indexPath.row % 7 == 0 
            return CGSize(width: collectionViewWidth, height: collectionViewWidth)
        

        if indexPath.row % 7 == 1 || indexPath.row % 7 == 2 || indexPath.row % 7 == 3 
            adjustedWidth = collectionViewWidth - (spaceBetweenCells * 2)
            return CGSize(width: floor(adjustedWidth / 3), height: floor(adjustedWidth / 3))
        

        if indexPath.row % 7 == 4 
            adjustedWidth = collectionViewWidth - spaceBetweenCells * 2
            return CGSize(width: floor(adjustedWidth / 3) * 2 + spaceBetweenCells, height: floor(adjustedWidth / 3) * 2 + spaceBetweenCells)
        

        if indexPath.row % 7 == 5 || indexPath.row % 7 == 6 
            adjustedWidth = collectionViewWidth - spaceBetweenCells * 2
            return CGSize(width: floor(adjustedWidth / 3), height: floor(adjustedWidth / 3))
        

        let width: CGFloat = adjustedWidth / 2
        let height: CGFloat = width;
        return CGSize(width: width, height: height)
    

结果如下:

我什至尝试为最后两个单元格使用较小的高度,以确保高度不是问题。感谢您的帮助。


更新 我通过 UIStackViews 让它工作了,虽然很烦人。

【问题讨论】:

为什么不用 UIStackView?为集合视图中的每个项目提供大小似乎很痛苦。 您的意思是使用 UIStackViews 的组合而不是 UICollectionView?我必须管理视图的入队/出队,那么不是吗?这似乎更痛苦。 我的意思是两者的结合。 【参考方案1】:

仅使用UICollectionViewFlowLayoutsizeForItem 方法并不是一件容易的事。你必须使用

if indexPath.row % 7 == 0 || indexPath.row % 7 == 4 
    return CGSize(width: collectionViewWidth, height: collectionViewWidth)

然后在cellForItemAt方法内:

if indexPath.row % 7 == 4 
    // Provide a UIStackView with your required layout
    // Or maybe even you could provide a smaller UICollectionView with just 3 cells, but that seems like overkill.

【讨论】:

我会试试这个——我相信它会起作用。但是,我很好奇这是否是正确的方法。感谢您的想法!

以上是关于UICollectionViewLayout - 2 列中的 3 个单元格的主要内容,如果未能解决你的问题,请参考以下文章

UICollectionViewLayout 教程

我应该继承啥 UICollectionViewLayout 或 UICollectionViewFlowLayout

使用缓存的 UICollectionViewLayoutAttributes 子类化 UICollectionViewLayout

UICollectionViewLayout - 2 列中的 3 个单元格

为啥将 UICollectionViewLayout 分配给 UICollectionView 后 UICollectionViewCells 不再可见?

自定义 UICollectionViewLayout 不同的单元格大小