Wednesday, 2 July 2014

Get page number from UIScrollView




UIScrollView plays a vital role when we need content to scroll horizontally or vertically in iPhone app development.We want to show images horizontally and one image will be displayed per page.For this requirement we can create our UIScrollView with setting its contentSize and adding our UIImageView as a subview to our UIScrollView.

                                      To get the  page number from our UIScrollView when user scrolls we will use - (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView method.This method fired automatically when UIScrollView stops scrolling. Now we will calculate page using simple formula of dividing contentOffset with UIScrollView width. To get round value, we will use lround function. Then, we check if previous page is not equal to current page(on we calculated )  means user scrolled to another page otherwise if its equal to previous value then user is on same page and did not scroll UIScrollView completely. Below is the code for the above explanation


Also please set UIScrollView delegate to self and also enabled paging property of your UIScrollView.

scroll.delegate = self;

scroll.pagingEnabled=YES;


- (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);

}


ScrollView get Page Number


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


No comments:
Write comments