Detect page change in UICollectionView Detect page change in UICollectionView ios ios

Detect page change in UICollectionView


Swift 3 Xcode 8.2

func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {        let x = scrollView.contentOffset.x        let w = scrollView.bounds.size.width        let currentPage = Int(ceil(x/w))        // Do whatever with currentPage.}


Use :

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{    CGFloat pageWidth = collectionView.frame.size.width;    float currentPage = collectionView.contentOffset.x / pageWidth;    if (0.0f != fmodf(currentPage, 1.0f))    {        pageControl.currentPage = currentPage + 1;    }    else    {        pageControl.currentPage = currentPage;    }    NSLog(@"Page Number : %ld", (long)pageControl.currentPage);}

And if you are not using any pageControl, then ceil(currentPage) will be your current page number.


Based on @Shankar BS 's answer I've implemented it like this in Swit. Keep in mind that CollectionViewDelegate conforms to ScrollViewDelegate:

func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {    let pageWidth = scrollView.frame.size.width    let page = Int(floor((scrollView.contentOffset.x - pageWidth / 2) / pageWidth) + 1)    print("page = \(page)")}


matomo