【问题标题】:Swift - How to fetch a UICollectionViewCell from UICollectionView based on index position in integerSwift - 如何根据整数中的索引位置从 UICollectionView 获取 UICollectionViewCell
【发布时间】:2017-10-11 13:34:36
【问题描述】:

我得到一个 int 形式的数据索引。我正在获取我的数据的位置,可以是 1 或 2 或 3 或 4 .. 等等。我如何使用这些 int 从 collectionview 中获取 colletionviewcell。

在每次滚动时,我都会将单元格的索引设为 int,例如,最初下一次滑动时它将为 0,数字将为 1,下一次滑动编号将为 2,依此类推。

    func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {
            let layout = self.collectionView.collectionViewLayout as! UICollectionViewFlowLayout
            let cellWidthIncludingSpacing = layout.itemSize.width + layout.minimumLineSpacing
            var offset = targetContentOffset.pointee
            let index = (offset.x + scrollView.contentInset.left) / cellWidthIncludingSpacing
            let roundIndex = round(index)
            offset = CGPoint(x: roundIndex * cellWidthIncludingSpacing - scrollView.contentInset.left, y: -scrollView.contentInset.top)
            targetContentOffset.pointee = offset

for cell in collectionView.visibleCells as! [CaurosalCollectionViewCell] {
            // do something

            print(cell.title.text)
        }
    }

expected output

【问题讨论】:

  • 你想从哪里获取单元格?滚动?
  • 在 scrollViewWillEndDragging 上是的
  • 您无法检索单元格,因为它尚未出现在屏幕上。您能更具体地说明您要做什么吗?
  • 更新了问题

标签: ios swift


【解决方案1】:

您可以使用 yourCollectionView?.indexPathsForVisibleItems 但它返回一个数组。 因此,您必须计算在当前 contentOffset 处可见的 indexPath。

类似:

func scrollViewDidScroll(_ scrollView: UIScrollView) {
    let visibleRect = CGRect(origin: yourCollectionView.contentOffset, size: yourCollectionView.bounds.size)
    let visiblePoint = CGPoint(x: CGFloat(visibleRect.midX), y: CGFloat(visibleRect.midY))
    let visibleIndexPath: IndexPath? = yourCollectionView.indexPathForItem(at: visiblePoint)
}

编辑

您需要查看 UICollectionViewLayout,特别是 layoutAttributesForItem(at indexPath: IndexPath)。您可以根据当前的 IndexPath 更新布局,而无需通过滚动视图委托。

如果您希望使用 scollview 代表,我相信这个问题在这里得到更好的回答:How to create a centered UICollectionView like in Spotify's Player

【讨论】:

  • 我已经更新了有问题的函数,我需要根据 roundIndex 获取单元格。我得到“无法将'CGFloat'类型的值转换为预期的参数类型'CGPoint'”我没有CGPoint我正在调整中心的水平collectionview单元格,我需要增加它的z位置
  • 你能检查我的代码如何根据roundIndex变量获取单元格
【解决方案2】:

您可以从此索引创建 indexpath,提供部分(我将其设为 0)。如果没有部分,则为零。此外,通过这个索引路径来获取单元格, 现在您必须将单元格类型转换为所需的类型,然后您才能使用它

 let indexpath = IndexPath(row: index, section: 0)
 guard let cell = collectionView.cellForItem(at: indexpath) as? CaurosalCollectionViewCell else { return }

【讨论】:

  • 我无法获取我的单元格,它总是在返回声明中
猜你喜欢
  • 2018-01-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-05-22
  • 2018-04-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多