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.
Using
followedCollectionView.indexPathsForVisibleItems()
to get visible cellsvisibleIndexPaths
and check yourindexPath
is contained invisibleIndexPaths
or not, before doing anything with cells. Ref : @anhtu Check whether cell at indexPath is visible on screen UICollectionViewAlso from Apple :
var visibleCells: [UICollectionViewCell] { get }
. Returns an array of visible cells currently displayed by the collection view.Here is a complete example of a "full screen" vertical scrolling collection view controller, with paging enabled (5 solid color cells). When the cell has "snapped into place" it will trigger
scrollViewDidEndDecelerating
where you can get the index of the current cell and perform whatever actions you like.Add a new
UICollectionViewController
to your storyboard, and assign its class toVerticalPagingCollectionViewController
. No need to change any of the default settings for the controller in storyboard - it's all handled in the code below: