Home > Net >  Cant get correct indexPath of collectionView cell
Cant get correct indexPath of collectionView cell

Time:05-19

EDIT: I try to get a correct indexPath of a current cell in a collectionView.

The project is simple: an album of photos and a label with a text. Text in label should be the current indexPath.

Concerning photos - everything is ok. Problem is with indexPath parameter in a label.

First right swipe changes indexPath for 2 instead of 1: from [0,0] to [0,2] - instead of [0,1]. Right swipes that have been made after this work correctly. But first left swipe changes the value of indexPath for -3. For example, if indexPath was [0,6] - the first left swipe will change it to [0, 3].

I have made a 10-sec video, representing a problem: https://www.youtube.com/shorts/Qxqr_Q9SDJ8 The buttons are made in order it would be easier to notice changes. They work like right/left swipe. Native swipes give the same result.

The code is this one:

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)"

CodePudding user response:

Problem is here

label.text = "testIndexPath: \(testIndexPath)"

When you swipe left/right to show a cell , In addition to showing the needed cell the collection may call that same method for the cell before/after to the center one as a preparation for display causing the label to change to it's value , so you need to keep an instance variable inside that viewController and increase/decrease it when you swipe right/left respectively

CodePudding user response:

You can override scrollViewDidScroll method and get the visible cell's indexPath when swiped:

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)"
    }
}

CodePudding user response:

i think you should use collectionview.indexPathForVisibleItems to get the indexPath when collectionView end scroll.

you can check collectionView end scroll by this: Swift 4 UICollectionView detect end of scrolling

  • Related