Home > Blockchain >  Make page control work only for 1 collection view(multiple collectionViews in View Controller)
Make page control work only for 1 collection view(multiple collectionViews in View Controller)

Time:05-13

I have 3-4 collectionViews in a page and one of them has page control which is working as expected. The problem is its also working when I scroll through cells of other collection views. So the dots will move regardless of whichever collectionView I'm scrolling through while it should only move for 1st collectionView. Here is how I'm enabling paging for 1 collectionView which is probably applying for every collection view:

 override func viewDidLoad() {
    super.viewDidLoad()

    // Do any additional setup after loading the view.
    //Collection View Delegates & Datasource
    let flowLayout = UICollectionViewFlowLayout()
    flowLayout.itemSize = CGSize(width: UIScreen.main.bounds.size.width, height: cvGarages.frame.size.height)
    flowLayout.scrollDirection = .horizontal
    flowLayout.minimumLineSpacing = 0
    collectionView1.collectionViewLayout = flowLayout
    collectionView1.isPagingEnabled = true
    collectionView1.showsHorizontalScrollIndicator = false
    collectionView1.delegate = self
    collectionView1.dataSource = self
    
    let flowLayout2 = UICollectionViewFlowLayout()
    flowLayout2.itemSize = CGSize(width: 171, height: 232)
    flowLayout2.scrollDirection = .horizontal
    flowLayout2.minimumLineSpacing = 0
    flowLayout2.minimumInteritemSpacing = 0
    collectionView2.collectionViewLayout = flowLayout2
    collectionView2.contentInset = UIEdgeInsets(top: 0, left: 7, bottom: 0, right: 0)
    collectionView2.delegate = self
    collectionView2.dataSource = self
    
    //Page Control
    pageControl.numberOfPages = 4  
}

//ScrollView delegate method
func scrollViewDidScroll(_ scrollView: UIScrollView) {
    let pageWidth = scrollView.frame.width
    self.currentPage = Int((scrollView.contentOffset.x   pageWidth / 2) / pageWidth)
    self.pageControl.currentPage = self.currentPage
}

CodePudding user response:

In scrollViewDidScroll() method check if scrollView is equal to (===) the specific collectionView. === operator will check the reference point of same instance.

public func scrollViewDidScroll(_ scrollView: UIScrollView) {
    if scrollView ===  self.collectionView1 {
        let pageWidth = scrollView.frame.width
        self.currentPage = Int((scrollView.contentOffset.x   pageWidth / 2) / pageWidth)
        self.pageControl.currentPage = self.currentPage
    }
}
  • Related