0

Im trying to implement infinite scroll on a collection view which has a custom layout.

after search I found this method:

    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()
    }

}

however, the print statement gets called multiple times causing a lot of cells to be inserted in collection view, sometimes it even get called 20 consecutive times.

is there a workaround ?

Moaz Ahmed
  • 441
  • 2
  • 8

1 Answers1

1

I Found a Solution:

    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
    }

}
Moaz Ahmed
  • 441
  • 2
  • 8