Add UIPageControl to UIScrollView

2019-07-04 19:10发布

问题:

I have a UIScrollView containing 5 images. I want to add a UIPageControl at the bottom of my scroll view so that the user can see what page they are on.

Here is my code for the scroll view:

self.helpScrollView.contentSize = CGSizeMake(320 * 5, 436);

UIImageView *image1 = [[UIImageView alloc] initWithFrame:CGRectMake(320 * 0, 0, 320, 436)];
image1.image = [UIImage imageNamed:[NSString stringWithFormat:
                                   @"Guide Page One.png"]];
[self.helpScrollView addSubview:image1];

UIImageView *image2 = [[UIImageView alloc] initWithFrame:CGRectMake(320 * 1, 0, 320, 436)];
image2.image = [UIImage imageNamed:[NSString stringWithFormat:
                                    @"Guide Page Two.png"]];
[self.helpScrollView addSubview:image2];

UIImageView *image3 = [[UIImageView alloc] initWithFrame:CGRectMake(320 * 2, 0, 320, 436)];
image3.image = [UIImage imageNamed:[NSString stringWithFormat:
                                    @"Guide Page Three.png"]];
[self.helpScrollView addSubview:image3];

UIImageView *image4 = [[UIImageView alloc] initWithFrame:CGRectMake(320 * 3, 0, 320, 436)];
image4.image = [UIImage imageNamed:[NSString stringWithFormat:
                                    @"Guide Page Four.png"]];
[self.helpScrollView addSubview:image4];

UIImageView *image5 = [[UIImageView alloc] initWithFrame:CGRectMake(320 * 4, 0, 320, 436)];
image5.image = [UIImage imageNamed:[NSString stringWithFormat:
                                    @"Guide Page Five.png"]];
[self.helpScrollView addSubview:image5];

self.helpScrollView.pagingEnabled = true;
self.helpScrollView.showsHorizontalScrollIndicator = NO;

I have dragged a UIPageControl onto my scrollview in my xib file, but I don't know how to link them. How do I do this?

回答1:

You don't want to add the UIPageControl to the scroll view itself because you don't want it to scroll with the content.

With that said, take a look at the UIScrollViewDelegate protocol, specifically scrollViewDidEndDecelerating: which will be called when your scroll view stops moving (a good time to update your UIPageControl).

Your calculation is going to be something like..

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
   self.pageControl.currentPage = floorf(scrollView.contentOffSet.x/320);
}

Re: I have two scroll views within one view controller, so does this specify which one I'm using?

The scrollView instance passed in can be used to negotiate which scroll view did end decelerating. If you set the delegate property for both of your scroll views this will get called when either of those end decelerating so you'll need to verify which instance ended decelerating.

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
   if (scrollView == self.helpScrollView) {
       self.pageControl.currentPage = floorf(scrollView.contentOffset.x/scrollView.frame.size.width);
   }
}