如何获取当前单元格的indexPath

How to get the indexPath of the current cell

我目前正在尝试创建一种方法来删除位于 1 back 的 indexPath 的集合视图中的项目。到目前为止,我已经使用一些帮助来创建一个函数,其中 scrollview 确实滚动以创建一种方法来计算用户通过当前图像方法查看的图像。我现在需要一种方法来计算用户所在的单元格。这是我的代码>

 var currentImage = 0
   func scrollViewDidScroll(_ scrollView: UIScrollView) {
let x = floor(myCollectionView.contentOffset.x / view.frame.width)
if Int(x) != currentImage {
    currentImage = Int(x)
    //print(currentImage)
}
if currentImage > 0 {
                for collectionCell in myCollectionView.visibleCells  as [UICollectionViewCell]    {
        let indexPath = myCollectionView.indexPath(for: collectionCell as UICollectionViewCell)!
       let indexPathOfLastItem = (indexPath?.item)! - 1
            let indexPathOfItemToDelete = IndexPath(item: (indexPathOfLastItem), section: 0)
            imageArray.remove(at: 0)
            myCollectionView.deleteItems(at: [indexPathOfItemToDelete])
            currentImage =  1

更多地基于评论而不是您的实际问题,您似乎想要的是获取第一个可见单元格的索引路径,以便您可以使用该路径删除单元格。

let visibleCells = myCollectionView.visibleCells
if let firstCell = visibleCells.first() {
    if let indexPath = myCollectionView.indexPath(for: collectionCell as UICollectionViewCell) {
        // use indexPath to delete the cell
    }
}

None 应该在 scrollViewDidScroll 委托方法中使用或完成。

[针对 Swift 5.2 进行了更新] 这里有一种比@rmaddy 的回答更简洁的方法(但那个方法工作得很好):

guard let indexPath = collectionView.indexPathsForVisibleItems.first else {
    return
}

// Do whatever with the index path here.