user1715916 user1715916 - 1 year ago 89
iOS Question

Change Page When Tapping on Pagecontrol in Swift

I know this questions has been answered before on here but I was unable to find an answer using Swift. Currently I have a pageviewcontroller embedded in a container view. The container view is inside the same viewcontroller as the pagecontrol. I'm using a delegate to get the pagecontrol to change when paging back and forth but currently the pages do not change when tapping on the pagecontrol dots. How can I do this in Swift?

The answers I have found on here answer the question but not with a pageviewcontroller.

Answer Source

My situation was different from the answers provided in the link. I had a viewpagecontroller in container view and followed this tutorial and the second one where there is an explanation given for the page control.

So I went to the parent viewcontroller with the container view and created a global variable:

var pagerController: MainPageViewController!

Then used:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if (segue.identifier == "PagerContainerSegue") {
        //This is used to reference the paging left and right functions
        let childViewController = segue.destination as! MainPageViewController
        pagerController = childViewController

Then I added an outlet for the pagecontrol when the value changed:

@IBAction func pageControlValueChange(_ sender: AnyObject) {
    //setViewControllers comes from the pageviewcontroller
    if(pageIndex == 0){
                                              direction: .forward,
                                              animated: true,
                                              completion: nil)
        pageIndex += 1

                                               direction: .reverse,
                                               animated: true,
                                               completion: nil)
        pageIndex -= 1

The pageIndex is assigned here:

func mainPageViewController(_ mainPageViewController: MainPageViewController,
                                didUpdatePageIndex index: Int) {
    pageIndex = index
    pageControl.currentPage = index
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download