【问题标题】:Collection View Cell leaving space on top集合视图单元格在顶部留下空间
【发布时间】:2017-12-20 14:03:21
【问题描述】:

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

Required Image

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

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)
}

如何解决单元格上方的空间问题。

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

【问题讨论】:

  • 您使用的是自定义UICollectionViewLayout ???
  • @ReinierMelian 不,我使用的是默认流布局。

标签: ios uiscrollview uicollectionview uicollectionviewdelegateflowlayout


【解决方案1】:

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

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

我最近做了一个,非常成功地关注了 Ray Wenderlich 的 this guide

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-19
    • 2022-07-05
    • 2017-11-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多