简体   繁体   中英

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.

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){
        pagerController.setViewControllers([orderedViewControllers[1]],
                                              direction: .forward,
                                              animated: true,
                                              completion: nil)
        pageIndex += 1

    }else{
        pagerController.setViewControllers([orderedViewControllers[0]],
                                               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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM