我正在尝试在具有自定义布局的 Collection View 上实现无限滚动。
经过搜索我找到了这个方法:
override func scrollViewDidScroll(_ scrollView: UIScrollView) {
//make sure collection view is on screen
if collectionView?.window == nil { return }
let offsetY = scrollView.contentOffset.y
let contentHeight = scrollView.contentSize.height
if offsetY > contentHeight - scrollView.frame.size.height {
print("scroll ended")
getNextTenProducts()
collectionView?.reloadData()
}
}
然而,多次调用print语句导致在 Collection View 中插入大量单元格,有时甚至连续调用20次。
有解决办法吗?
最佳答案
我找到了解决方案:
override func scrollViewDidScroll(_ scrollView: UIScrollView) {
if collectionView?.window == nil { return }
let offsetTolerance = CGFloat(30)
let offsetY = scrollView.contentOffset.y
let contentHeight = scrollView.contentSize.height
if offsetY > contentHeight - scrollView.frame.size.height + offsetTolerance, !scrollViewReachedBottom {
print("scroll ended")
scrollViewReachedBottom = true
} else if offsetY < contentHeight - scrollView.frame.size.height - offsetTolerance {
scrollViewReachedBottom = false
}
}
关于swift - 实现无限滚动时多次调用 scrollViewDidLoad,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40031213/