Search code examples
iosobjective-cswiftscrollviewcollectionview

iOS - scrollViewDidEndDecelerating runs for both scrollView and collectionView


I have a VC that contains a collectionView and a scrollView. I put this code to change current page of pageController by scrolling in scrollView :

func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {

    let pageNumber = round(scrollView.contentOffset.x / scrollView.frame.size.width)
    self.pageController.currentPage = Int(pageNumber)
}

It works nice for scrollView but the problem is when i even scroll in collectionView it declares and causes unwanted changing in pageController!

What should i do?


Solution

  • In addition to the answers posted above, You can make use of the tag property of the view.

    Just assign a tag (Int) to your scrollview either in xib or via code.

    yourScrollView.tag = 10
    

    And in the scrollview delegate method check for this tag:

    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
    
        if scrollView.tag == 10 { 
          ///Your scrollview was scrolled
        } else {
          // Collection view was scrolled
        }
    
    }