iosswiftcollectionviewindexpathsegmentedcontrol

Change UISegmentedControl.selectedIndex value depending on which UICollectionViewCell is currently shown


how can I change the UISegmentedControl.selectedIndex value depending on which UICollectionViewCell is currently shown? My collectionView has the isPagingEnabled set to true, and I can easily select a different item depending on the selected index of my UISegmentedControl, but how can I do the opposite?

Is there a function that gets called called every time the user changes page of the collectionView that also gives the indexPath of the currently shown item?

Accessing the visibleCells array doesn't seem to be any useful. A function like

func collectionViewDidPage(_ collectionView: UICollectionView, _ fromIndexPath: IndexPath, _ toIndexPath: IndexPath) {
    let tag = myCollectionView.cellForItem(at: toIndexPath).tag
    self.segmentedControl.selectedSegmentIndex = tag
}

where fromIndexPath and toIndexPath are the indexPaths of the two cells (the one from which I started scrolling and the one I'm going to end scrolling) could work.

What can I do?


Solution

  • The following code seems to be working pretty fine:

    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        let pageNumber = round(scrollView.contentOffset.x / scrollView.frame.size.width)
        segmentedControl.selectedSegmentIndex = Int(pageNumber)
    }