編輯: 我嘗試在 collectionView 中獲取當前單元格的正確 indexPath。
這個專案很簡單:一個相冊和一個帶有文字的標簽。標簽中的文本應該是當前的 indexPath。
關于照片 - 一切都很好。問題在于標簽中的 indexPath 引數。
第一次向右滑動將 indexPath 更改為 2 而不是 1:從 [0,0] 到 [0,2] - 而不是 [0,1]。在此之后進行的正確滑動可以正常作業。但是第一次向左滑動將 indexPath 的值更改為 -3。例如,如果 indexPath 為 [0,6] - 第一次向左滑動會將其更改為 [0, 3]。
我制作了一個 10 秒的視頻,代表一個問題:https ://www.youtube.com/shorts/Qxqr_Q9SDJ8 制作這些按鈕是為了更容易注意到變化。它們像右/左滑動一樣作業。本機滑動給出相同的結果。
代碼是這樣的:
var currentIndexPath: IndexPath = [0,0]
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! CollectionViewCell
var testIndexPath = indexPath
cell.imageView.image = allPhotos[testIndexPath.item].faceCard
return cell
}
func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
currentIndexPath = indexPath
}
label.text = "\(currentIndexPath)"
uj5u.com熱心網友回復:
您可以覆寫scrollViewDidScroll方法并在滑動時獲取可見單元格的 indexPath:
func scrollViewDidScroll(_ scrollView: UIScrollView) {
let visibleRect = CGRect(origin: collectionView.contentOffset, size: collectionView.bounds.size)
let visiblePoint = CGPoint(x: visibleRect.midX, y: visibleRect.midY)
if let testIndexPath = collectionView.indexPathForItem(at: visiblePoint) {
label.text = "testIndexPath: \(testIndexPath)"
}
}
uj5u.com熱心網友回復:
我認為您應該在 collectionView 結束滾動時使用 collectionview.indexPathForVisibleItems 來獲取 indexPath。
您可以通過以下方式檢查 collectionView 結束滾動: Swift 4 UICollectionView detect end of scrolling
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/477703.html
