UICollectionView: current index path for page control UICollectionView: current index path for page control ios ios

UICollectionView: current index path for page control


You can get the current index by monitoring contentOffset in scrollViewDidScroll delegate

it will be something like this

-(void)scrollViewDidScroll:(UIScrollView *)scrollView{    NSInteger currentIndex = self.collectionView.contentOffset.x / self.collectionView.frame.size.width;}


Get page via NSIndexPath from center of view.

Works even your page not equal to width of UICollectionView.

func scrollViewDidScroll(scrollView: UIScrollView) {    let xPoint = scrollView.contentOffset.x + scrollView.frame.width / 2    let yPoint = scrollView.frame.height / 2    let center = CGPoint(x: xPoint, y: yPoint)    if let ip = collectionView.indexPathForItemAtPoint(center) {        self.pageControl.currentPage = ip.row    }}


Definitely you need catch the visible item when the scroll movement is stopped. Use next code to do it.

func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {    if let indexPath = myCollectionView.indexPathsForVisibleItems.first {        myPageControl.currentPage = indexPath.row    }}


matomo