Swift-在collectionView.isPagingEnabled=true时阻止快速滚动



我有一个启用了分页的collectionView:

collectionView.isPagingEnabled = true

collectionView是全屏的(一次只显示一个单元格(,我有一些代码在scrollViewWillEndDragging中运行。当我正常或半快速滚动时,cellForItemscrollViewWillEndDragging在同一页/indexPath.item上。但当我滚动得很快时,它们都会出错,cellForItem总是在当前页面后面

**启用分页时,如何防止用户快速滚动?

var currentItem: Int?
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeue...
currentItem = indexPath.item
return cell
}
func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {
let yAxis = targetContentOffset.pointee.y
let page = Int(yAxis / collectionView.frame.height)
guard let currentItem = currentItem else { return }
if page == currentItem {
// only do something when page and the current indexPath.item are equal which works fine with normal scrolling
}
}

这个答案有效:

func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
scrollView.isUserInteractionEnabled = false
}
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
scrollView.isUserInteractionEnabled = true
}

相关内容

最新更新