Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to update UIPageControl when UIScrollView with PagingEnabled changes page?

How do i make it so that when the user scrolls to a new page in UIScrollView, the UIPageControl updates?

like image 490
Andrew Avatar asked Jun 10 '11 17:06

Andrew


3 Answers

I have used this before and it seemed to work well. Be sure to set the UIScrollView.delegate to self.

#pragma mark - UIScrollViewDelegate methods

- (void)scrollViewDidEndDecelerating:(UIScrollView *)sender {
    uint page = sender.contentOffset.x / width;
    [self.pageControl setCurrentPage:page];
}
like image 146
picciano Avatar answered Jan 04 '23 23:01

picciano


Where you defined your UIScrollView and UIPageControl, you have to implement this method :

- (void)scrollViewDidScroll:(UIScrollView *)_scrollView
{
    if (pageControlIsChangingPage)
        return;

    CGFloat pageWidth = _scrollView.frame.size.width;
    int page = floor((_scrollView.contentOffset.x - pageWidth / 2) / pageWidth) + 1;
    pageControl.currentPage = page;
}

and this one :

- (void)scrollViewDidEndDecelerating:(UIScrollView *)_scrollView 
{
    pageControlIsChangingPage = NO;
}

where pageControlIsChangingPage is :

BOOL    pageControlIsChangingPage;
like image 42
Pierre Espenan Avatar answered Jan 05 '23 00:01

Pierre Espenan


Here is an update of this answer for Swift as well:

func scrollViewDidEndDecelerating(scrollView: UIScrollView) {
            pageControl.currentPage = Int(myScrollView.contentOffset.x) / Int(myScrollView.frame.width)
        }
like image 22
Jack Amoratis Avatar answered Jan 04 '23 23:01

Jack Amoratis