Get page number from UIScrollView

Getting page number from UIScrollView

In order to get  page number form UIScrollView, we need to implement UIScrollView delegate method names
 
scrollViewDidEndDecelerating
 

This methods gets called when UIScrollView gets to halt or stopped after scrolling the content, Thus at this point we can get  the page number by calculating the width of UIScrollview and its content offset.

Before implementing the code, few things needs to be set up

scroll.delegate = self;
scroll.pagingEnabled=YES;

Swift Code:

func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        
        let pageWidth = scrollView.frame.size.width
        let fractionalPage = scrollView.contentOffset.x / pageWidth
        let page = lround(Double(fractionalPage))
        if previousPage != page {
            //page chnaged
            previousPage = page
        }

Objective C code:

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    CGFloat pageWidth = scrollView.frame.size.width;
    float fractionalPage = scrollView.contentOffset.x / pageWidth;
    NSInteger page = lround(fractionalPage);
    if (previousPage != page) {
        // Page has changed, do your thing!
        // ...
        // Finally, update previous page
        previousPage = page;
    }
    NSLog(@"previous page == %d",previousPage);
}

NOTE:- previousPage is declared in .h of viewCntroller as i need to use it somewhere else.You can declare it as NSInteger previousPage;