James Cockerham James Cockerham - 8 days ago 5
iOS Question

How to advance page in uipageviewcontroller with uibutton on uiviewcontroller/storyboard

I have a very specific use case that I am wondering if anyone has dealt with. I want to add a "Continue" button on my first time user experience UIPageViewController. This article (Swift iOS: how to trigger next page using buttons), touches if you want it to be on every page, but I am not planning that broad of use.

I have a UIPageViewController, and 6 viewcontrollers that I currently can navigate through by swiping.

I've tried connecting the button to the view controller as a segue, but that presents it outside of the PageViewController. I've thought of trying to just push a right to left swipe onto the button click, but I couldn't quit figure that out.

Anyone have an idea on how to attack putting a single button on one of the view controllers and have it progress to the next view controller within the UIPageViewController?




This was marked as duplicate, but there are no duplicate cases of this issue on SO. There are few similar, but nothing like it. If there is one, please link it. The currently linked version is an obj-c answer to a similar question with no explanation as to how to link the needed function to the view controller. That answer I can implement as a global button easily, but a single view controllers button is not covered by it.

Thanks

Answer

Walk up the view controller hierarchy to find the page view controller. When you find it, ask it to turn the page:

@IBAction func nextPageButtonWasTapped(_ sender: AnyObject?) {
    var candidate: UIViewController = self
    while true {
        if let pageViewController = candidate as? UIPageViewController {
            candidate.navigateForward()
            break
        }
        guard let next = parentViewController else { break }
        candidate = next
    }
}

Implement navigateForward in an extension on UIPageViewController, based on the Objective-C version from this answer.