集合视图单元格将 space 留在顶部

Collection View Cell leaving space on top

我在垂直滚动模式下使用具有不同单元格大小的集合视图。我希望单元格如图所示。

Required Image

但是集合视图单元格看起来像这样,顶部有额外的 space。

Image from my project

下面是项目中的代码:

 func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int{
        return self.allProducts.count
    }

 func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "demoItem", for: indexPath) as! ItemCollectionViewCell
    let item = allProducts[indexPath.row]
    cell.lbl_name.text = item.title
    cell.lbl_price.text = "$ " + item.price
    cell.imgView.image = imgArray[indexPath.row % imgArray.count]

    return cell
}

  func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    if indexPath.row % 3 == 0
    {
        return CGSize(width: collectionView.frame.size.width/2, height: 200)
    }
    else if indexPath.row % 2 == 0
    {
        return CGSize(width: collectionView.frame.size.width/2, height: 225)
    }
   return CGSize(width: collectionView.frame.size.width/2, height: 250)
}

如何解决 space 上面的单元格问题。

注意:我已经尝试将 automaticallyEdgeInset 设置为 false 并手动更改 contentInsets 但没有任何反应。

在我看来,您使用的是典型的流式布局,它创建的行的高度为该行中最高项目的高度,并使该行中的所有项目垂直居中。我的猜测是单元格不会占用所有 space(可能是因为自动布局和图像大小?)。

无论是什么原因,您似乎都在尝试从上到下尽可能靠近地放置单元格,忽略行。

我最近制作了其中一个,非常成功地遵循了 Ray Wenderlichthis guide