Sean Danzeiser
Sean Danzeiser

Reputation: 9243

UIPageControl showing incorrect page

I've got a UIScrollView containing several tables, and a UIPageControl keeping track of which page the user is currently viewing. It works fine UNTIL i start scrolling up on the tableview, at which point the UIPageControl adjusts and says (incorrectly) that we are on the first page.

Here is my code:

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

  /*
   *  We switch page at 50% across
   */
  CGFloat pageWidth = _scrollView.frame.size.width;
  int page = floor((_scrollView.contentOffset.x - pageWidth / 2) / pageWidth) + 1;
  pageControl.currentPage = page;
}

and then this as well:

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

Not sure what exactly is causing this to happen . . . any ideas? Im stumped :(

Upvotes: 1

Views: 1091

Answers (2)

Sean Danzeiser
Sean Danzeiser

Reputation: 9243

I believe the issue was that both the UITableView and the UIScrollView, since they both had the delegates set to self, were calling the same scrollview methods. I added a tag to the main scrollview, and then accounted for it by performing a check on the Tag when adjusting the page, like so

if (_scrollView.tag == 100) {

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

}

finally

Upvotes: 2

Kjuly
Kjuly

Reputation: 35191

When you scroll the page, does it scrolls correctly?

if (pageControlIsChangingPage)
  return;

It seems when you do not change page (i.e. you scroll the tableview instead), return'll not be executed. And so

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

part will be executed, at this moment, _scrollView.contentOffset.x will less than pageWidth / 2 (even can be 0), as you just scroll up/down, and as a result, the page turn out to be 1.

Upvotes: 0

Related Questions