gpt4 book ai didi

ios - 如何检测 UICollectionViewCell 的中点何时位于 UICollectionView 的框架之外?

转载 作者:行者123 更新时间:2023-11-29 05:16:23 25 4
gpt4 key购买 nike

我知道下面的 UITableViewDataSource 方法会在整个单元格被隐藏时通知我。

func collectionView(_ collectionView: UICollectionView, didEndDisplaying cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {}

但我需要一种方法,可以在单元格的一半隐藏时通知我。

换句话说,我需要一个方法,当单元格滚动到一半单元格可见而一半不可见时,该方法将被触发。

最佳答案

确实没有一个简单的方法可以解决这个问题。但这应该可以解决问题。您想要做的是检测 collectionView 何时滚动,然后确定哪些单元格完全可见以及哪些单元格的中心“在屏幕外”。如果某个单元格最近完全可见,但中心不再出现在屏幕上,我们可以假设该单元格大约有 50% 可见。

为此,您需要跟踪哪些单元格最近完全可见,然后当单元格的中心移出屏幕时,从列表中删除该单元格。如果您不从列表中删除该单元格,那么它将被重复处理,因为它的中心将在多次滚动检测迭代中离开屏幕。

class ViewController: UICollectionViewController {

// ...

var recentlyFullyVisibleCells: Set<IndexPath> = .init()

func processOffScreenCell(at indexPath: IndexPath) {
guard let cell = collectionView.cellForItem(at: indexPath) else { return }
cell.backgroundColor = .red
}

func processFullyVisibleCell(at indexPath: IndexPath) {
guard let cell = collectionView.cellForItem(at: indexPath) else { return }
cell.backgroundColor = .white
}

override func scrollViewDidScroll(_ scrollView: UIScrollView) {

let latestFullyVisibleCells = collectionView.visibleCells.filter { cell in
// Get cells that are fully visible
let rect = collectionView.convert(cell.frame, to: collectionView.superview)
return collectionView.frame.contains(rect)
}
.compactMap { cell in
// Convert to IndexPath
collectionView.indexPath(for: cell)
}

latestFullyVisibleCells.forEach { indexPath in
processFullyVisibleCell(at: indexPath)
}

collectionView.visibleCells.filter { cell in
// Get cells whose center are not on screen
let rect = collectionView.convert(cell.frame, to: collectionView.superview)
return !collectionView.frame.contains(CGPoint(x: rect.midX, y: rect.midY))
}
.compactMap { cell in
// Convert to IndexPath
collectionView.indexPath(for: cell)
}
.reduce(into: Set<IndexPath>()) { result, indexPath in
// Convert to Set
result.insert(indexPath)
}
.intersection(recentlyFullyVisibleCells) // Only keep cells that were recently fully visible
.forEach { indexPath in
processOffScreenCell(at: indexPath)
recentlyFullyVisibleCells.remove(indexPath)
}

recentlyFullyVisibleCells.formUnion(latestFullyVisibleCells)
}

override func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
recentlyFullyVisibleCells.removeAll()
}

// ...

}

关于ios - 如何检测 UICollectionViewCell 的中点何时位于 UICollectionView 的框架之外?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59147654/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com