Updated 9 days ago | GitHub

Using UIPageControl

While UIPageViewController comes with its own UIPageControl, it’s often useful to add your own, so you have greater control over its placement. Also, sometimes you don’t want a full UIPageViewController, but you just want a UIScrollView with paging enabled.

Step 1: Add and configure UIScrollView

  • Add a UIScrollView to the storyboard.
  • Create an outlet from the Scroll View.
  • Add the UIScrollViewDelegate protocol to your ViewController. ScrollViewDelegate gif
  • Within the viewDidLoad method, set the scroll view delegate and turn on paging with isPagingEnabled, so the scroll view stops on multiples of its own bounds and the page calculation in Step 3 lands on whole pages. Set the content size in viewDidLayoutSubviews, deriving it from the scroll view’s own size so it is correct on every device — the scroll view’s bounds are not final yet in viewDidLoad. Your content size will vary according to how big your scrollable area is; this example is three pages wide.
override func viewDidLoad() {
    super.viewDidLoad()
    scrollView.delegate = self
    scrollView.isPagingEnabled = true
}

override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()
    // 3 pages of horizontal content, each the size of the scroll view itself
    scrollView.contentSize = CGSize(width: scrollView.bounds.width * 3,
                                    height: scrollView.bounds.height)
}

Step 2: Add the UIPageControl

In the Storyboard, add a UIPageControl to the view controller. Often, you will place it on top of, not inside of, the UIScrollView.

  • Add a UIPageControl to the Storyboard.
  • Create an outlet from the Page Control

Step 3: Register for scroll events

Register for the UIScrollView scroll event, for example, you can update the UIPageControl every time the UIScrollView stops moving.

func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
    // Get the current page based on the scroll offset, using the scroll view's
    // own width as the page width so this works on every device size.
    let pageWidth = scrollView.bounds.width
    guard pageWidth > 0 else { return }
    let page = Int(round(scrollView.contentOffset.x / pageWidth))

    // Set the current page, so the dots will update
    pageControl.currentPage = page
}

Step 4: Customize Page Control Properties

You can configure the number of dots as well as the color of the unselected or selected dots.

Number of dots to display: You can set the number of pages for the page control to show as dots.
If I had four pages, I would set…

pageControl.numberOfPages = 4

Color of current page dot:

pageControl.currentPageIndicatorTintColor = UIColor.red

For more details, see Registering for Scroll Events.