【问题标题】:How to find index path of last visible cell in collection view. but index path is random keeps changing如何在集合视图中查找最后一个可见单元格的索引路径。但索引路径是随机的不断变化
【发布时间】:2017-08-02 08:34:29
【问题描述】:

我已尝试使用以下代码从 collectionview 中找出最后一个可见索引路径,但可见单元格不断变化,我无法找到最后一个可见项目。

for cell: UICollectionViewCell in collView.visibleCells {
     // indexPath = collView.indexPathForCell(cell)!
        var visibleRect = CGRect()
        visibleRect.origin = collView.contentOffset
        visibleRect.size = collView.bounds.size
        let visiblePoint = CGPoint(x: visibleRect.width, y: visibleRect.height)
        if  let indexPath = collView.indexPathForItem(at: visiblePoint) //If let is
        {
            return indexPath
        } else {
            return IndexPath(row: NSNotFound, section: 0)
        }

}

输出

"<NSIndexPath: 0x17422c680> {length = 2, path = 0 - 4}",
"<NSIndexPath: 0x17403e0c0> {length = 2, path = 0 - 6}",
"<NSIndexPath: 0x1742261c0> {length = 2, path = 0 - 10}",
"<NSIndexPath: 0x17422adc0> {length = 2, path = 0 - 1}",
"<NSIndexPath: 0x1742205e0> {length = 2, path = 0 - 3}",
"<NSIndexPath: 0x17422a1a0> {length = 2, path = 0 - 7}",
"<NSIndexPath: 0x174227080> {length = 2, path = 0 - 9}",
"<NSIndexPath: 0x174229b40> {length = 2, path = 0 - 0}"

【问题讨论】:

  • 你能展示一下你的收藏视图是什么样子的吗?
  • 同照片应用

标签: uicollectionview cell nsindexpath


【解决方案1】:

您可以使用indexPathsForVisibleItems 获取UICollectionView 中可见项目的indexPaths 数组。

var indexPathsForVisibleItems: [IndexPath] { get }

该属性的值是一个未排序的 IndexPath 对象数组, 每个都对应于集合视图中的一个可见单元格。 该数组不包括当前存在的任何补充视图 可见的。如果没有可见项目,则此属性的值为 一个空数组。

就像您指定的照片应用程序一样,您将在数组中获得多个 IndexPath 元素,因为在特定时刻有多个元素可见。

另外,我不明白你所说的最后一个可见索引是什么意思。请更清楚地说明以获得任何进一步的帮助。

编辑:

示例: 我创建了一个 UICollectionView,其中包含 30 个单元格和 1 个部分。 对于以下屏幕:

我使用了以下代码行:

    let arrayOfVisibleItems = collectionView.indexPathsForVisibleItems.sorted()
    let lastIndexPath = arrayOfVisibleItems.last
    print("Array: ", arrayOfVisibleItems)
    print("Last IndexPath: ", lastIndexPath)        

输出:

Array:  [[0, 0], [0, 1], [0, 2], [0, 3], [0, 4], [0, 5], [0, 6], [0, 7], [0, 8], [0, 9], [0, 10], [0, 11], [0, 12], [0, 13], [0, 14], [0, 15], [0, 16], [0, 17], [0, 18], [0, 19], [0, 20]]

Last IndexPath:  Optional([0, 20])

【讨论】:

  • 我使用了与上面相同的方法,但我想让最后一个项目在集合视图中可见。就像我有八个项目可见并且我想要八个项目的索引路径
  • 如果你想要最后一个,你可以使用数组的最后一个属性,即arrayOfVisibleItems.last
  • 但我认为我错了 indexpath 就像我给出了输出请检查
  • 我已经编辑了答案。让我知道它是否满足您的要求。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-02-02
  • 1970-01-01
  • 2019-04-14
  • 1970-01-01
  • 2011-02-21
相关资源
最近更新 更多