【问题标题】:UICollectionView column grid gapsUICollectionView 列网格间隙
【发布时间】:2013-01-03 10:52:19
【问题描述】:

我在我的 iPad 应用程序中使用 UICollectionView 流布局。我有不同宽度和高度的单元格。当我使用UICollectionViewFlowLayout 的子类作为集合视图的布局时,它显示了单元格之间的间隙。

如果列中有大单元格,它会使该列的网格和小单元格呈现在列中该大单元格的中心。 有没有更好的方法来紧紧包裹细胞?

我正在使用水平滚动。我尝试使用layoutAttributesForElementsInRect: 方法,但没有成功。

如果有人使用layoutAttributesForElementsInRect: 方法或其他方式做过同样的事情,请告诉我...

请查找附件图片。我需要同样的解决方案

提前谢谢...

【问题讨论】:

    标签: objective-c ios uicollectionview


    【解决方案1】:

    这样使用

    UICollectionViewFlowLayout *layout=[[UICollectionViewFlowLayout alloc] init];
    
    layout.minimumInteritemSpacing = 0;
    layout.minimumLineSpacing = 2;
    

    【讨论】:

      【解决方案2】:

      我对 UICollectionViewFlowLayout 进行了子类化,并且在我的 layoutAttributesForItemAtIndexPath: 和 layoutAttributesForElementsInRect: 方法中我有一个方法称为

      setLineAttributes:(UICollectionViewLayoutAttributes *)attributes visibleRect:(CGRect)visibleRect:
      

      其中包含:

      if (attributes.indexPath.item == 0 || attributes.indexPath.item == 1 || attributes.indexPath.item == 2) {
          CGRect f = attributes.frame;
          f.origin.x = 0;
          attributes.frame = f;
      } else {
          NSIndexPath *ipPrev = [NSIndexPath indexPathForItem:attributes.indexPath.item - 3 inSection:attributes.indexPath.section];
          CGRect fPrev = [self layoutAttributesForItemAtIndexPath:ipPrev].frame;
          CGFloat rightPrev = fPrev.origin.x + fPrev.size.width + 10;
          if (attributes.frame.origin.x <= rightPrev) 
              return;
      
          CGRect f = attributes.frame;
          f.origin.x = rightPrev;
          attributes.frame = f;
      }
      

      【讨论】:

      • 在上面的代码中你假设会有 3 行。但情况并非总是如此。假设我的应用程序不知道每个单元格的宽度和高度(假设它来自服务器或者它将决定运行时间),在这种情况下,我们需要手动计算行数和列数。然后我们需要根据相邻的单元格框架计算每个单元格的原点。我不知道这是最好的方法还是有别的方法。但无论如何感谢您的回复。
      • 行数不是总是相同的,不一定是 3,而是一定的行数。
      • 是的.. 但集合视图不提供行数和列数。当我们有不同大小的(宽度和高度)项目时,我们还需要手动计算行数和列数。有没有更好的办法?