Swift - 当 collectionView.isPagingEnabled = true 时防止快速滚动
Swift -prevent fast scrolling when collectionView.isPagingEnabled = true
我有一个启用了分页的 collectionView:
collectionView.isPagingEnabled = true
collectionView 是全屏的(一次只显示 1 个单元格),我有一些代码在 scrollViewWillEndDragging
中运行。当我正常或半快速滚动时,cellForItem
和 scrollViewWillEndDragging
在同一个 page/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
}
}
这个answer有效:
func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
scrollView.isUserInteractionEnabled = false
}
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
scrollView.isUserInteractionEnabled = true
}
我有一个启用了分页的 collectionView:
collectionView.isPagingEnabled = true
collectionView 是全屏的(一次只显示 1 个单元格),我有一些代码在 scrollViewWillEndDragging
中运行。当我正常或半快速滚动时,cellForItem
和 scrollViewWillEndDragging
在同一个 page/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
}
}
这个answer有效:
func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
scrollView.isUserInteractionEnabled = false
}
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
scrollView.isUserInteractionEnabled = true
}