简体   繁体   中英

How to get the indexPath of the current cell

I have currently trying to create a way to delete an item in a collection view at the indexPath of 1 back. So far i have used some help to create a function with scrollview did scroll to create a way to count which image the user is on by the current image method. I now need a way to count which cell the user is on. Here is my code>

 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

Based more on the comments than your actual question, what you seem to want is to get the first visible cell's index path so you can use that path to delete the cell.

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 of this should be used or done in the scrollViewDidScroll delegate method.

[Updated for Swift 5.2] Here's a slightly more succinct way than @rmaddy's answer (but that one works just fine):

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

// Do whatever with the index path here.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM