Page Controls

I am working on converting a client's app to auto layout. Currently the views are set up in code using hard set CGPoints to place objects in the view. This worked okay on the 3.5 inch screens when the app initially launched but Apple has moved on from that screen size, so we have to as well. 

One piece of the puzzle is setting up a new page controller. Page controllers are the little dots you see on your home screen and in various apps with more than one horizontal view. Those dots tell you how many pages there are total and which one you are currently on. 

Most of the configuration of the page control can be done in interface builder without touching code except for the last little bits. Here are the steps I took to make this page control work.

First -- drag over your page control from the list in the Utilities area and constrain it in your layout.

Next create two outlets from your new page control and add the UIScrollViewDelegate to your classes interface file.

@interface Main : UIViewController <UIScrollViewDelegate>

@property (weak, nonatomic) IBOutlet UIScrollView *scrollView;
@property (strong, nonatomic) IBOutlet UIPageControl *pageControl;

* Don't forget to connect the delegate to the scroll view. * (This is starred because I forgot to do this initially and it took some extra time to find.)

Next you can configure the scroll view and page control in interface builder.

'# of Pages' is the total number of pages (dots) you want shown. 'Current' is which dot you want to start on. This count starts from 0 so if you want to start on the first dot make sure you use '0' not '1'. 

Also make sure your scroll view have scrolling and paging enabled.

Lastly the easy part, coding it up.

- (void)scrollViewDidScroll:(UIScrollView *)scrollView 
{
    CGFloat pageWidth = self.scrollView.frame.size.width;
    int page = floor((self.scrollView.contentOffset.x - pageWidth / 2) / pageWidth) + 1;
    self.pageControl.currentPage = page;
}

Using the delegate method 'scrollViewDidScroll' you can control which dot is highlighted once the user scrolls more than 50% of the scroll view. If you have a different number of pages you'll need to edit the code for your own use.

 

Sources:

iOS Developer Library -- Page Control

iOS Developer Library -- UIPageControl Class Reference

Page Control for Switching Between Views