Search code examples
swiftuicollectionviewuiscrollview

scrollViewDidScroll not called in a CollectionView with custom layout


I want to load more data when the user reaches the end of my CollectionView. Unfortunately, scrollViewDidScroll is never called.

For my CollectionView, I use a custom layout and I think the problem could be at this:

    if let layout = exploreCollectionView.collectionViewLayout as? CustomLayout {
        layout.delegate = self
    }

My class:

class MainViewController: UIViewController, UIScrollViewDelegate { .....

I want to check if the function scrollViewDidScroll works:

    // Check if a user wants to load more data at the bottom
func scrollViewDidScroll(_ scrollView: UIScrollView) {
    print("scrolled")
}

How do I implement the scrollViewDidScroll in my CustomLayout?


Solution

  • scrollViewDidScroll is a UIScrollViewDelegate method. So you need to make self (MyViewController) a delegate of the collectionview:

    exploreCollectionView.delegate = self

    And then for instance in an extension:

    extension MyViewController: UIScrollViewDelegate {
       func scrollViewDidScroll(_ scrollView: UIScrollView) {
          print("scrolled")
       }
    }