Search code examples
iosswiftuiviewcontrolleruibuttonuipageviewcontroller

How to change UIPageViewController VCs by UIButton Swift 4.0?


I have UIPageViewController with 3 UIViewControllers ("FirstVC", "SecondVC", "ThirdVC"). ViewControllers changes by scroll, but I need to change its by click on UIButtons.

How I can do this?

Maybe some func, in which VC will setup by StoryboardID?

Thanks for all answers!


Solution

  • You can easily programmatically navigate through the pages of a UIPageViewController using:

    setViewControllers([targetPage], direction: .forward, animated: true, completion: nil)
    

    In the case where you have a UIPageViewController embedded in a ContainerView, and you want buttons in the "root" view to control the page view controller, the basic process is:

    • add navigation methods (funcs) to your page view controller class
    • save a reference to the page view controller when it is loaded have
    • your buttons call the navigation funcs using that reference

    When your "root" view controllers loads and instantiates the view controller that is embedded in your ContainerView, it calls prepare(for segue:...) - which is where you get your reference.

    In Storyboard, where you embed your view controller in the ContainerView, you will see a standard "segue" connection. In the Attributes Inspector, give that segue an Identifier, such as "PageControllerEmbedSegue".

    In your root controller class, add a class-level var:

    var myPageVC: BasicPageViewController?
    

    and in prepare():

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    
        // get a reference to the embedded PageViewController on load
        if let vc = segue.destination as? BasicPageViewController,
            segue.identifier == "PageControllerEmbedSegue" {
            self.myPageVC = vc
        }
    
    }
    

    Now, you can call functions / get properties of your embedded view controller.

    I have a full example on GitHub: https://github.com/DonMag/EmbeddedPageView