Search code examples
iosswiftuiscrollviewuicollectionviewuicollectionviewcell

Check if cell completely displayed in collectionview


I have a collection view where the cell is of the size exactly to the collectionView, so each cell should occupy the whole screen. I have implemented a functionality where the cell is snapped to the complete view whenever it's dragged or decelerated through the scroll. This is how the UX works.

https://drive.google.com/open?id=1v8-WxCQUzfu8V_k9zM1UCWsf_-Zz4dpr

What I want:

As you can see from the clip, the cell snaps to the whole screen. Now, I want to execute a method after it snaps. Not before or not when it's partially displayed.

Following is the code I have written for snapping effect :

func scrollToMostVisibleCell(){
    let visibleRect = CGRect(origin: collectionView.contentOffset, size: collectionView.bounds.size)
    let visiblePoint = CGPoint(x: visibleRect.midX, y: visibleRect.midY)
    let visibleIndexPath = collectionView.indexPathForItem(at: visiblePoint)!
    collectionView.scrollToItem(at: visibleIndexPath as IndexPath, at: .top, animated: true)
    print("cell is ---> ", visibleIndexPath.row)
}



func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
    scrollToMostVisibleCell()
}

func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
    scrollToMostVisibleCell()
    if !decelerate {
        scrollToMostVisibleCell()
    }
}

If I use willDisplayCell method, then it' just going to return me as soon as the cell is in the view, even if it's just peeping in the collectionView.

Is there a way where I can check if the cell is completely in the view and then I can perform a function?

I have scrapped the internet over this question, but ain't able to find a satisfactory answer.


Solution

  • Using followedCollectionView.indexPathsForVisibleItems() to get visible cells visibleIndexPaths and check your indexPath is contained in visibleIndexPaths or not, before doing anything with cells. Ref : @anhtu Check whether cell at indexPath is visible on screen UICollectionView

    Also from Apple : var visibleCells: [UICollectionViewCell] { get } . Returns an array of visible cells currently displayed by the collection view.