【问题标题】:cellForItemAt indexPath gives an issue when collection view is scrolled滚动集合视图时,cellForItemAt indexPath 会出现问题
【发布时间】:2018-11-26 09:41:06
【问题描述】:

我有一个部分的collectionView,部分中的numberOfItems 是100。我正在根据cellforItemAt indexPath 方法中的条件加载集合视图,即

if (indexPath.row % 5 == 0) {
 cellWidth = 100
} else {
 cellWidth = 50
}

这会正确加载集合视图,但是当我滚动集合视图时无法按预期工作。

图片 1 是我所期待的 图 2 是滚动集合视图时得到的结果。

【问题讨论】:

  • 什么是有效的,什么不是预期的?
  • 图像 1 是我所期望的,但是当我向上和向下滚动时,集合视图正在更改为图像 2。
  • 条件的实际作用是什么?
  • 尝试在collectionView中启用分页collectionView.isPagingEnabled = true。当且仅当红色标签位于 UICollectionViewCell 的中心时,它才有效。
  • @iPeter 它决定了单元格内内容的宽度。

标签: ios swift collectionview


【解决方案1】:

因为单元格是可重复使用的,所以我建议你改变内部的宽度,而不是像这样给出宽度值

 func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {

    if indexPath.row % 5 == 0 {
      return CGSize(width: 100, height:10)
    }else {
      return CGSize(width:50, height:10 
    }
}

【讨论】:

  • 感谢 Alpher,您的解决方案解决了我的问题。
【解决方案2】:

要确定单元格内内容的宽度,我建议使用sizeForItemAtIndexPath,如下所示:

首先让你的控制器符合协议UICollectionViewDelegateFlowLayout并实现方法:

extension YourViewController: UICollectionViewDelegateFlowLayout {

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        if indexPath.row % 5 == 0 {
            return CGSize(width: 100, height: YourCellHeight)
        } else {
            return CGSize(width:50, height: YourCellHeight) 
        }
    }
}

【讨论】:

  • 如果解决方案解决了您的问题,请将答案标记为已接受,以便将来帮助其他人。 :)
【解决方案3】:

tableView 中也出现滚动问题,CellView 中有一个名为 prepareForReuse() 的函数,您可以使用它来解决此问题;在您的情况下,您应该重置 cellWidth 的值,因为有时在滚动 collectionView 时,变量会变得混乱

在你的 CollectionViewCell 中你可以像这样调用这个函数

override func prepareForReuse() {
    super.prepareForReuse()
    cellWidth = nil
}

了解您的单元格是自定义单元格还是普通 UICollectionViewCell 会很有帮助

【讨论】:

  • 感谢您的建议,但这并没有解决我的问题,我使用的是普通的 UICollectionViewCell。
  • 好的,你可以使用其他人发给你的函数 sizeForItemAt :)
猜你喜欢
  • 2017-02-25
  • 2018-01-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-02-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多