我试图在具有自定义布局的集合视图上实现无限滚动。
搜索后我发现了这个方法: 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语句会导致很多单元格被插入到集合视图中,有时甚至连续调用20次。
有解决方法吗?
答案 0 :(得分:1)
我找到了一个解决方案:
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
}
}