Sergey_VC
Sergey_VC

Reputation: 103

Cant get correct indexPath of collectionView cell

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

Upvotes: 0

Views: 648

Answers (2)

Jayce Nguyen
Jayce Nguyen

Reputation: 116

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

Upvotes: 1

Nandish
Nandish

Reputation: 1162

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

Upvotes: 1

Related Questions