简体   繁体   中英

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

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
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM