Repository navigation
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.
- Add a UIScrollView to the storyboard.
- Create an outlet from the Scroll View.
- Add the
UIScrollViewDelegateprotocol to your ViewController. - Within the
viewDidLoadmethod, set the scroll view delegate. Set the content size inviewDidLayoutSubviews, 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 inviewDidLoad. 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
}
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)
}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
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
}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 = 4Color of current page dot:
pageControl.currentPageIndicatorTintColor = UIColor.redFor more details, see Registering for Scroll Events.