Detecting UIScrollView page change

Pompair picture Pompair · Mar 11, 2011 · Viewed 53k times · Source

Is there a way to detect or get a notification when user changes the page in a paging-enabled UIScrollView?

Answer

Michael Waterfall picture Michael Waterfall · Mar 11, 2011

Use this to detect which page is currently being shown and perform some action on page change:

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    static NSInteger previousPage = 0;
    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;
    }
}

If it's acceptable for you to only react to the page change once the scrolling has completely stopped, then it would be best to do the above inside the scrollViewDidEndDecelerating: delegate method instead of the scrollViewDidScroll: method.