在启用分页的情况下检测 scrollView 中取消的滚动

detect canceled scroll in scrollView with paging enabled

我想检测用户何时滚动到下一页(在启用分页的 collectionView 中)。一旦用户开始滚动到下一个单元格,我就使用 collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) 函数准备它。这里我设置了一个变量,指示下一个可见单元格。

然后,当用户停止拖动时,我 运行 使用 scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) 函数更新视觉效果。此时我知道哪个单元格是可见的,因为我之前将其保存在变量中。

但是,当用户开始拖动 collectionView 然后滚动回起始视图时,collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) 已经保存了下一个项目。这导致以下函数 (scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool)) 到 运行 不正确的代码(视觉更新)。

有什么方法可以知道用户何时取消或实际执行了滚动到下一页,以便我可以停止 scrollViewDidEndDragging 更新,除非滚动是 "successful"?

你可以比较didStartDragging和didEndDragging的scrollview的.contentOffset。 分页动画成功当且仅当 contentOffset 改变

解决方案是使用函数 scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) 并查看 targetContentOffset 参数。如果它在任一方向上都超过页面宽度的一半,则滚动成功。