Custom UIPagecontrol in swift

UIPageControl in IOS is a control that is used mostly in help screens or info screens for IOS apps. In this post, we are going to create a small tutorial for UIPageControl in swift language. And in this tutorial,  we will change background color of UIImageView as per page number selected by user on tapping on UIPageControl. And also, on scroll of UIScrollView i.e. when user scrolled UIScrollView. UIScrollView is used with UIPageControl as the page control itself is set of dots and does not has its own display interface.

https://iostutorialjunction.com/2015/05/uipagecontrol-tutorial-ios-objective-c.html

Implementation of UIPageControl in swift

Lets start our tutorial of creating custom page control or UIPageControl in swift language. Create a new project with single view application template, name it UIPageViewController-swift. Next, open Main.storyboard and drop UIScrollView and UIpagecontrol on to the view.

Drag UIscrollView and UIPageControl on to view
Drag UIscrollView and UIPageControl on to view

Adding constraints to the controls (UIPageControl and UIScrollView)

First, add leading, trailing, bottom, top constraints to UIScrollView. Secondly, we will add constraint to page control / UIPageControl. And finally we will add horizontal and top constraint with respect to scrollview.

Add constraints to UIScrollView
Add constraints to UIScrollView
Add constraints to UIPageControl
Add constraints to UIPageControl

Creating IBOutlet for UIPageControl and UIScrollView

Now open ViewController.swift and create IBOutlets for UIPageControl and UIScrollView

@IBOutlet var pageControl: UIPageControl?
@IBOutlet var scrollView: UIScrollView?
var scrollWidth : CGFloat = UIScreen.main.bounds.size.width
var scrollHeight : CGFloat = UIScreen.main.bounds.size.height

add an IBAction named changePage that we are going to assign to UIPageControl ValueChanged event. So that we can detect user tap on UIPageControl

@IBAction func changePage(){

}

At this stage, your ViewController.swift file will look like this

class ViewController: UIViewController {
    @IBOutlet var pageControl: UIPageControl?
    @IBOutlet var scrollView: UIScrollView?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    @IBAction func changePage(){
        
    }
}

Open Main.storyboard, first connect IBOutlet and secondly IBAction to both UIScrollView and UIPageControl. Lastly, set minimum number of page to UIPageControl

Connecting UIPageControl IBOutlet
Connecting UIPageControl IBOutlet
Connecting IBOutlet to UIScrollView
Connecting IBOutlet to UIScrollView
Setting number of pages in out UIPageControl and setting current page number
Setting number of pages in out UIPageControl and setting current page number

Note: scrollWidth and scrollHeight are the width and height calculated with respect to empty space we left on top, bottom,left right or our UIScrollView with respect to view.

Use below code to create 3 pages for our UIPageControl

override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        print((scrollView?.frame.size.width)!)
        scrollView?.contentSize = CGSize(width: (scrollWidth * 3), height: scrollHeight)
        scrollView?.delegate = self;
        scrollView?.isPagingEnabled=true
        
        for i in 0...2 {
            let imgView = UIImageView.init()
            imgView.frame = CGRect(x: scrollWidth * CGFloat (i), y: 0, width: scrollWidth,height: scrollHeight)
            imgView.backgroundColor = UIColor.red
            if i == 0 {
                imgView.backgroundColor = UIColor.green
            }
            
            if i == 1 {
                imgView.backgroundColor = UIColor.blue
                imgView.image = UIImage(named: "2.jpg")
            }
            
            scrollView?.addSubview(imgView)
        }
    }

Run you code and you will see colored UImageViews inside your scroll. Swipe left and right, and you will see page effect. But still we have to implement our page control as user can also tap on page control in order to navigate through the different pages of UIScrollView.

Final Source code to achieve pagination for our UIPageControl and UIScrollView

In our changePage action, we will use scrollRectToVisible method of UIScrollView. So that we can scroll our UIScrollView as per user tap on UIPageControl.

@IBAction func changePage(){
         scrollView!.scrollRectToVisible(CGRectMake( scrollWidth * CGFloat ((pageControl?.currentPage)!), 0, scrollWidth, scrollHeight), animated: true)
    }

Lastly. we need to implement scrollViewDidEndDecelerating delegate of UIScrollView so that we can calculate page number if user did not use UIPageControl and simple scroll down UIScrollView

func scrollViewDidEndDecelerating(scrollView: UIScrollView) {
       setIndiactorForCurrentPage()
    }
    
    func setIndiactorForCurrentPage()  {
       let page = (scrollView?.contentOffset.x)!/scrollWidth
        pageControl?.currentPage = Int(page)

    }

In setIndicatorForCurrentPage, we calculated page by diving x offset of UIScrollView with its width and the assign that page to our UIPageControl as its current or selected page.

Download source code from here

Where to go from here:

In this post we learn about how to use/create custom UIPageControl in iOS using swift language. You can check Custom UIPageControl objective C version from here UIPageControl tutorial in objective C 
I hope you enjoyed the post, how to create custom UIPageControl in IOS Tutorial – Swift.