0
votes

I want to detect when a user scrolls to the next page (in a collectionView with paging enabled). As soon as the user begins scrolling to the next cell i prepare it using the collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) function. Here I set a variable indicating which will be the next visible cell.

Then, when the user stops dragging, I run the visual updates using the scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) function. At this point I know which cell is visible because I saved that in the variable before.

However, when the user starts dragging the collectionView and then scrolls back to the starting view, the collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) already saved the next item. This leads the following function (scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool)) to run incorrect code (visual updates).

Is there any way of knowing when a user canceled or actually executed a scroll to the next page, so that I can stop scrollViewDidEndDragging from updating unless the scroll was "successful"?

2

2 Answers

0
votes

You can compare the scrollview’s .contentOffset from didStartDragging and didEndDragging. The paging animation is successful if and only if the contentOffset changed

0
votes

The solution was using the function scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) and looking at the targetContentOffset parameter. if the it is more than half the width of the page in either direction, the scrolling was successful.